[Go to site: main page, start]

0% found this document useful (0 votes)
2 views3 pages

Java Code Exercises

Uploaded by

Peter Mwangi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views3 pages

Java Code Exercises

Uploaded by

Peter Mwangi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

Hello and Name Printer

Write a Java program to print 'Hello' on screen and your name on a separate line.
Expected Output:
Hello
Alexandra Abramov

public class Exercise1 {


public static void main(String[] args) {
// Print a greeting message to the console
[Link]("Hello\nAlexandra Abramov!");
}
}

2. Sum of Two Numbers

Write a Java program to print the sum of two numbers.


Test Data:
74 + 36
Expected Output:
110

public class Exercise2 {


public static void main(String[] args) {
// Calculate the sum of 24 and 26
int sum = 24 + 26;
// Print the result of the addition
[Link](sum);
}
}

3. Division of Two Numbers

Write a Java program to divide two numbers and print them on the screen.
Test Data:
50/3
Expected Output:
16public class Exercise3 {

public static void main(String[] args) {


// Calculate the result of the division 50/3
int result = 50 / 3;

// Print the result of the division


[Link](result);
}
}

4. Arithmetic Operations

Write a Java program to print the results of the following operations.


Test Data:
a. -5 + 8 * 6
b. (55+9) % 9
c. 20 + -3*5 / 8
d. 5 + 15 / 3 * 2 - 8 % 3
Expected Output:
43
1
19
13

public class Exercise4 {


public static void main(String[] args) {
// Calculate and print the result of the expression: -5
+ 8 * 6
[Link](-5 + 8 * 6);

// Calculate and print the result of the expression: (55


+ 9) % 9
[Link]((55 + 9) % 9);

// Calculate and print the result of the expression: 20


+ -3 * 5 / 8
[Link](20 + -3 * 5 / 8);

// Calculate and print the result of the expression: 5 +


15 / 3 * 2 - 8 % 3
[Link](5 + 15 / 3 * 2 - 8 % 3);
}
}

5. Product of Two Numbers

Write a Java program that takes two numbers as input and displays the product of two numbers.
Test Data:
Input first number: 25
Input second number: 5
Expected Output:
25 x 5 = 125
import [Link];

public class Exercise5 {

public static void main(String[] args) {


// Create a Scanner object to read input from the user
Scanner in = new Scanner([Link]);

// Prompt the user to input the first number


[Link]("Input first number: ");
// Read and store the first number
int num1 = [Link]();

// Prompt the user to input the second number


[Link]("Input second number: ");
// Read and store the second number

// Calculate the product of the two numbers and display the


result
[Link](num1 + " x " + num2 + " = " + num1 * num2);
}
}

You might also like