Java Sample Codes
Java Sample Codes
Write a java program to add two integer numbers and display the sum
SOLUTION 1
if ( number1 == number2 )
System.out.printf( "%d == %d\n", number1, number2 );
if ( number1 != number2 )
System.out.printf( "%d != %d\n", number1, number2 );
SOLUTION
// Assign a radius
radius = 20; // New value is radius
// Compute area
area = radius * radius * 3.14159;
// Display results
Q6. . Write a java program to compute the area of a CIRCLE ,given, area = Pi X
R2, pi = 3.142 and radius = ?.
// Compute area
double area = radius * radius * 3.14159;
// Display result
System.out.println("The area for the circle of radius " + radius + " is " +
area);
}
}
// Compute average
double average = (number1 + number2 + number3) / 3;
// Display result
System.out.println("The average of " + number1 + " " + number2 + " " +
number3 + " is " + average);
}
}
Q8. Write a java program to convert second to minutes and show the remaining
seconds.
import java.util.Scanner;
Q9. Write a java program to display Message method that displays the course
name as part of the welcome message.
SOLUTION
package project1;
import java.util.Scanner;
/**
*/
myGradeBook.displayMessage( nameOfCourse );
}
package project1;
/**
*
* @author Engr. Abbas
*/
class GradeBook {
public void displayMessage( String courseName )
{
System.out.printf( "Welcome to the grade book for\n%s!\n",
courseName );
}
}
SOLUTION
import java.util.Scanner; // program uses class Scanner
// initialization phase
total = 0; // initialize total
gradeCounter = 1; // initialize loop counter
// processing phase
while ( gradeCounter <= 10 ) // loop 10 times
{
System.out.print( "Enter grade: " ); // prompt
grade = input.nextInt(); // input next grade
total = total + grade; // add grade to total
gradeCounter = gradeCounter + 1; // increment counter by 1
} // end while
// termination phase
average = total / 10; // integer division yields integer result
Q11. Write a java program for Prefix increment and postfix increment
operators. Given c =5.
SOLUTION
package project1;
/**
*
* @author Engr. Abbas
*/
public class Project1 {
/**
* @param args the command line arguments
*/
public static void main( String args[])
{
int c;
// demonstrate postfix increment operator
c = 5; // assign 5 to c
System.out.println( c ); // print 5
System.out.println( c++ ); // print 5 then postincrement
System.out.println( c ); // print 6
// end main
SOLUTION
SOLUTION
SOLUTION
// display headers
System.out.printf( "%s%20s\n", "Year", "Amount on deposit" );
SOLUTION
do
{
System.out.printf( "%d ", counter );
++counter;
} while ( counter <= 10 ); // end do...while
Index Value
0 32
1 27
2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37