Java: Print the sum, difference, product, average, distance, maximum and minimum
Arithmetic Operations on Two Integers
Write a Java program that accepts two integers from the user and prints the sum, the difference, the product, the average, the distance (the difference between the integers), the maximum (the largest of the two integers), and the minimum (the smallest of the two integers).
Test Data
Input 1st integer: 25
Input 2nd integer: 5

Sample Solution:
Java Code:
import java.util.Scanner;
public class Exercise9 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input 1st integer: ");
int firstInt = in.nextInt();
System.out.print("Input 2nd integer: ");
int secondInt = in.nextInt();
System.out.printf("Sum of two integers: %d%n", firstInt + secondInt);
System.out.printf("Difference of two integers: %d%n", firstInt - secondInt);
System.out.printf("Product of two integers: %d%n", firstInt * secondInt);
System.out.printf("Average of two integers: %.2f%n", (double) (firstInt + secondInt) / 2);
System.out.printf("Distance of two integers: %d%n", Math.abs(firstInt - secondInt));
System.out.printf("Max integer: %d%n", Math.max(firstInt, secondInt));
System.out.printf("Min integer: %d%n", Math.min(firstInt, secondInt));
}
}
Sample Output:
Input 1st integer: 25 Input 2nd integer: 5 Sum of two integers: 30 Difference of two integers: 20 Product of two integers: 125 Average of two integers: 15.00 Distance of two integers: 20 Max integer: 25 Min integer: 5
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Java program to perform arithmetic operations on two integers and then determine if the sum is prime.
- Write a Java program to compute the arithmetic operations on two integers using lambda expressions and functional interfaces.
- Write a Java program to accept two integers and then calculate their arithmetic operations without using the '+' or '-' operators.
- Write a Java program to compute arithmetic operations on two integers and output the results in a formatted table with alignment.
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Java program that reads a number and display the square, cube, and fourth power.
Next: Write a Java program to break an integer into a sequence of individual digits.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics