0% found this document useful (0 votes)
20 views15 pages

Java Sample Codes

Java sample programs solutions and answers.

Uploaded by

abbasmodibo19
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
20 views15 pages

Java Sample Codes

Java sample programs solutions and answers.

Uploaded by

abbasmodibo19
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 15

Q1.

Write a java program to add two integer numbers and display the sum

SOLUTION 1

// Fig. 2.7: Addition.java


// Addition program that displays the sum of two numbers.
import java.util.Scanner; // program uses class Scanner

public class Addition


{
// main method begins execution of Java application
public static void main( String args[] )
{
// create Scanner to obtain input from command window
Scanner input = new Scanner( System.in );

int number1; // first number to add


int number2; // second number to add
int sum; // sum of number1 and number2

System.out.print( "Enter first integer: " ); // prompt


number1 = input.nextInt(); // read first number from user

System.out.print( "Enter second integer: " ); // prompt


number2 = input.nextInt(); // read second number from user

sum = number1 + number2; // add numbers

System.out.printf( "Sum is %d\n", sum ); // display sum

} // end method main

} // end class Addition


Q2. Write a java program to to compute the area of a rectangle, given, area =
length X breadth.

Q3. Write a java program to Compare integers using if statements, relational


operators and equality operators.
SOLUTION

// Fig. 2.15: Comparison.java


// Compare integers using if statements, relational operators
// and equality operators.
import java.util.Scanner; // program uses class Scanner

public class Comparison


{
// main method begins execution of Java application
public static void main( String args[] )
{
// create Scanner to obtain input from command window
Scanner input = new Scanner( System.in );

int number1; // first number to compare


int number2; // second number to compare

System.out.print( "Enter first integer: " ); // prompt


number1 = input.nextInt(); // read first number from user

System.out.print( "Enter second integer: " ); // prompt


number2 = input.nextInt(); // read second number from user

if ( number1 == number2 )
System.out.printf( "%d == %d\n", number1, number2 );

if ( number1 != number2 )
System.out.printf( "%d != %d\n", number1, number2 );

if ( number1 < number2 )


System.out.printf( "%d < %d\n", number1, number2 );

if ( number1 > number2 )


System.out.printf( "%d > %d\n", number1, number2 );

if ( number1 <= number2 )


System.out.printf( "%d <= %d\n", number1, number2 );

if ( number1 >= number2 )


System.out.printf( "%d >= %d\n", number1, number2 );

} // end method main


} // end class Comparison

Q4. Write java program to calculate the product of three integers.


solution

// Ex. 2.6: Product.java


// Calculate the product of three integers.
import java.util.Scanner; // program uses Scanner

public class Product


{
public static void main( String args[] )
{
// create Scanner to obtain input from command window
Scanner input = new Scanner( System.in );

int x; // first number input by user


int y; // second number input by user
int z; // third number input by user
int result; // product of numbers

System.out.print( "Enter first integer: " ); // prompt for input


x = input.nextInt(); // read first integer

System.out.print( "Enter second integer: " ); // prompt for input


y = input.nextInt(); // read second integer

System.out.print( "Enter third integer: " ); // prompt for input


z = input.nextInt(); // read third integer

result = x * y * z; // calculate product of numbers

System.out.printf( "Product is %d\n", result );

} // end method main

} // end class Product


Q5. . Write a java program to compute the area of a CIRCLE ,given, area = Pi X
R2, pi = 3.142 and radius = 20.

SOLUTION

LISTING 2.1 ComputeArea.java


public class ComputeArea {
public static void main(String[] args) {
double radius; // Declare radius
double area; // Declare area

// Assign a radius
radius = 20; // New value is radius
// Compute area
area = radius * radius * 3.14159;

// Display results

System.out.println("The area for the circle of radius " +


radius + " is " + area);
}
}

Q6. . Write a java program to compute the area of a CIRCLE ,given, area = Pi X
R2, pi = 3.142 and radius = ?.

// Scanner is in the java.util package


import java.util.Scanner;
public class ComputeAreaWithConsoleInput {
public static void main(String[] args) {
// Create a Scanner object
Scanner input = new Scanner(System.in);

// Prompt the user to enter a radius


System.out.print("Enter a number for radius: ");
double radius = input.nextDouble();

// Compute area
double area = radius * radius * 3.14159;
// Display result
System.out.println("The area for the circle of radius " + radius + " is " +
area);
}
}

Q7. Write a java program to compute the average of three numbers

// Scanner is in the java.util package


import java.util.Scanner;
public class ComputeAverage {
public static void main(String[] args) {
// Create a Scanner object
Scanner input = new Scanner(System.in);

// Prompt the user to enter three numbers


System.out.print("Enter three numbers: ");
double number1 = input.nextDouble();
double number2 = input.nextDouble();
double number3 = input.nextDouble();

// 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;

public class DisplayTime {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user for input
System.out.print("Enter an integer for seconds: ");
int seconds = input.nextInt();
int minutes = seconds / 60; // Find minutes in seconds
int remainingSeconds = seconds % 60; // Seconds remaining
System.out.println(seconds + " seconds is " + minutes + " minutes and " +
remainingSeconds + " seconds");
}
}

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;

/**

* @author Engr. Abbas

*/

public class GradeBookTest {

public static void main( String args[] )

Scanner input = new Scanner( System.in );

GradeBook myGradeBook = new GradeBook();

System.out.println( "Please enter the course name:" );

String nameOfCourse = input.nextLine(); // read a line of text

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 );
}
}

Q10. Write a java program to solve class-average of 10 courses using counter-


controlled repetition.

SOLUTION
import java.util.Scanner; // program uses class Scanner

public class GradeBook


{

private String courseName; // name of course this GradeBook represents

// constructor initializes courseName


public GradeBook( String name )
{
courseName = name; // initializes courseName
} // end constructor
// method to set the course name
public void setCourseName( String name )
{
courseName = name; // store the course name
} // end method setCourseName

// method to retrieve the course name


public String getCourseName()
{
return courseName;
} // end method getCourseName
// display a welcome message to the GradeBook user
public void displayMessage()
{
// getCourseName gets the name of the course
System.out.printf( "Welcome to the grade book for\n%s!\n\n",
getCourseName() );
} // end method displayMessage

// determine class average based on 10 grades entered by user


public void determineClassAverage()
{
// create Scanner to obtain input from command window
Scanner input = new Scanner( System.in );

int total; // sum of grades entered by user


int gradeCounter; // number of the grade to be entered next
int grade; // grade value entered by user
int average; // average of grades

// 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

// display total and average of grades


System.out.printf( "\nTotal of all 10 grades is %d\n", total );
System.out.printf( "Class average is %d\n", average );
} // end method determineClassAverage

} // end class GradeBook

public class GradeBookTest


{
public static void main( String args[] )
{
// create GradeBook object myGradeBook and
// pass course name to constructor
GradeBook myGradeBook = new GradeBook( "CS101 Introduction to Java
Programming" );

myGradeBook.displayMessage(); // display welcome message


myGradeBook.determineClassAverage(); // find average of 10 grades
} // end main

} // end class GradeBookTest

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

System.out.println(); // skip a line


// demonstrate prefix increment operator
c = 5; // assign 5 to c
System.out.println( c ); // print 5
System.out.println( ++c ); // preincrement then print 6
System.out.println( c ); // print 6

// end main

// TODO code application logic here


}
}

Q12. Write a java program Counter-controlled repetition using while repetition


statement to count from 1 to 10.

SOLUTION

public class WhileCounter


{
public static void main( String args[] )
{
int counter = 1; // declare and initialize control variable

while ( counter <= 10 ) // loop-continuation condition


{
System.out.printf( "%d ", counter );
++counter; // increment control variable by 1
} // end while

System.out.println(); // output a newline


} // end main
} // end class WhileCounter

Q13. Write a java program Counter-controlled repetition using for statement


header includes initialization to count from 1 to 10.

SOLUTION

public class ForCounter


{
public static void main( String args[] )
{
// for statement header includes initialization,
// loop-continuation condition and increment
for ( int counter = 1; counter <= 10; counter++ )
System.out.printf( "%d ", counter );

System.out.println(); // output a newline


} // end main
} // end class ForCounter

Q14. Write a java program to compute compound interest calculation

SOLUTION

public class Interest


{
public static void main( String args[] )
{
double amount; // amount on deposit at end of each year
double principal = 1000.0; // initial amount before interest
double rate = 0.05; // interest rate

// display headers
System.out.printf( "%s%20s\n", "Year", "Amount on deposit" );

// calculate amount on deposit for each of ten years


for ( int year = 1; year <= 10; year++ )
{
// calculate new amount for specified year
amount = principal * Math.pow( 1.0 + rate, year );

// display the year and the amount


System.out.printf( "%4d%,20.2f\n", year, amount );
} // end for
} // end main
}
Q15. Write a java program Counter-controlled repetition using Do…while
repetition statement to count from 1 to 10.

SOLUTION

public class DoWhileTest


{
public static void main( String args[] )
{
int counter = 1; // initialize counter

do
{
System.out.printf( "%d ", counter );
++counter;
} while ( counter <= 10 ); // end do...while

System.out.println(); // outputs a newline


} // end main
} // end class DoWhileTest

Figure 7.5. Computing the sum of the elements of an array.


1 // Fig. 7.5: SumArray.java
2 // Computing the sum of the elements of an array.
3
4 public class SumArray
5 {
6 public static void main( String args[] )
7 {
8 int array[] = { 87, 68, 94, 100, 83, 78, 85, 91, 76,
87 };
9 int total = 0;
10
11 // add each element's value to total
12 for ( int counter = 0; counter < array.length; counter++
)
13 total += array[ counter ];
14
15 System.out.printf( "Total of array elements: %d\n",
total );
16 } // end main
17 } // end class SumArray

7.3. Write a java program to initialize the elements of an array with an


array initializer given the following as an array elements(32, 27, 64,
18, 95, 14, 90, 70, 60, 370).

1 // Fig. 7.3: InitArray.java


2 // Initializing the elements of an array with an array
initializer.
3
4 public class InitArray
5 {
6 public static void main( String args[] )
7 {
8 // initializer list specifies the value for each element
9 int array[] = { 32, 27, 64, 18, 95, 14, 90, 70,60, 37 };
10
11 System.out.printf( "%s%8s\n", "Index", "Value" ); // column
headings
12
13 // output each array element's value
14 for ( int counter = 0; counter < array.length; counter++ )
15 System.out.printf( "%5d%8d\n", counter,
array[ counter ] );
16 } // end main
17 } // end class InitArray

Index Value
0 32
1 27
2 64
3 18
4 95
5 14
6 90
7 70
8 60
9 37

Total of array elements: 849


Arrays are data structures consisting of related
data items of the same type. Arrays are fixed-
length entitiesthey remain the same length
once they are created, although an array
variable may be reassigned the reference of a
new array of a different length.

 An array is a group of variables (called


elements or components) containing
values that all have the same type.
Arrays are objects, so they are
considered reference types. The
elements of an array can be either
primitive types or reference types
(including arrays).
 To refer to a particular element in an
1. Java
array,code
wefor class Withdrawal
specify the name of based
the on Fig. 8.24 and Fig. 8.25.
reference to the array and the index
(subscript) of the element in the array.
 A program refers to any one of an
array's elements with an array-access
expression that includes the name of
the array followed by the index of the
particular element in square brackets
([]).
 The first element in every array has
index zero and is sometimes called the
zeroth element.
 An index must be a nonnegative
integer. A program can use an
expression as an index.
 Every array object knows its own
length and maintains this information
in a length field. The expression
array.length accesses array's length
field to determine the length of the
array.
 To create an array object, the
programmer specifies the type of the
array elements and the number of
elements as part of an array-creation
expression that uses keyword new. The
following array-creation expression
creates an array of 100 int values:
 int b[] = new int[
100 ];

 When an array is created, each element


of the array receives a default value
zero for numeric primitive-type
elements, false for boolean elements
and null for references (any
nonprimitive type).
 When an array is declared, the type of
the array and the square brackets can
be combined at the beginning of the
declaration to indicate that all the
identifiers in the declaration are array
variables, as in
 double[] array1, array2;
1 // Class Withdrawal represents an ATM withdrawal transaction
2 public class Withdrawal
3 {
4 // attributes
5 private int accountNumber; // account to withdraw funds
from
6 private double amount; // amount to withdraw
7
8 // no-argument constructor
9 public Withdrawal()
10 {
11 } // end no-argument Withdrawal constructor
12 } // end class Withdrawal

You might also like