Java program to perform all arithmetic operations

Write a Java program to perform all arithmetic operation. How to perform arithmetic operations in Java programming. In this example we will learn to input two integer from user and perform all arithmetic operations.

Example
Input

First number: 15
Second number: 4

Output

Sum : 19
Difference : 11
Product : 60
Quotient : 3
Modulus : 3

Java program to perform all arithmetic operations

Required knowledge

Arithmetic operators, Data types, Basic Input/Output

In previous example we learned to write simple Java program. We learned to read input from user and find sum of two numbers. In this example I will explain how to perform all basic arithmetic operations.

Program to perform all arithmetic operations

/**
 * Java program to perform all arithmetic operations.
 */
import java.util.Scanner;

public class ArithmeticOperation {

   public static void main(String[] args) {
        
        // Create scanner class object
        Scanner in = new Scanner(System.in);

        // Input two numbers from user
        System.out.println("Enter first number :");
        int num1 = in.nextInt();
        System.out.println("Enter second number :");
        int num2 = in.nextInt();
        

        // Perform arithmetic operations.
        int sum 		= num1 + num2;
        int difference 	= num1 - num2;
        int product 	= num1 * num2;
        int quotient	= num1 / num2;
        int modulo	    = num1 % num2;
        

        // Print result to console.
        System.out.println("Sum : "         + sum);
        System.out.println("Difference : "  + difference);
        System.out.println("Product : "     + product);
        System.out.println("Quotient : "    + quotient);
        System.out.println("Modulo : "      + modulo);
    }
}

Note: Here num1 and num2 both are int type. Hence, num1 / num2 yields integer division. To perform floating point division, you need to typecast either of them to float or double type.

For example:
double quotient = (double) num1 / num2; or
float quotient = (float) num1 / num2;

Output

Enter first number : 15
Enter second number : 4

Sum : 19
Difference : 11
Product : 60
Quotient : 3
Remainder : 3

Happy coding 😉

Comments and discussion
Have a doubt, write here. I will help my best.
Before commenting you must escape your source code before commenting. Paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>