Java Program to Perform Addition, Subtraction, Multiplication and Division

Perform Mathematical Operations

To perform mathematical operations such as addition, subtraction, multiplication and division of any two number in Java Programming, you have to ask to the user to enter the two number and then perform the action accordingly.

Java Programming Code for Addition Subtraction Multiplication Division

Following Java Program ask to the user to enter the two number and perform the addition, subtraction, multiplication and division on the two entered number by the user and then display the result on the screen:

```/* Java Program Example - Mathematical Operations */

import java.util.Scanner;

public class JavaProgram
{
public static void main(String args[])
{
int a, b, res;
Scanner scan = new Scanner(System.in);

System.out.print("Enter Two Numbers : ");
a = scan.nextInt();
b = scan.nextInt();

res = a + b;
System.out.println("Addition = " +res);

res = a - b;
System.out.println("Subtraction = " +res);

res = a * b;
System.out.println("Multiplication = " +res);

res = a / b;
System.out.println("Division = " +res);
}
}```

When the above Java Program is compile and executed, it will produce the following output:

Four Mathematical Operation in Java

Following Java program will ask to the user to enter the two number along with operator to perform the particular operation (addition, subtraction, multiplication and division) according to the user:

```/* Java Program Example - Four Mathematical Operations */

import java.util.Scanner;

public class JavaProgram
{
public static void main(String args[])
{
int a, b, res;
char ch;
Scanner scan = new Scanner(System.in);

System.out.print("Enter First Number : ");
a = scan.nextInt();
System.out.print("Enter Second Number : ");
b = scan.nextInt();
System.out.print("Enter Operator (+, -, *, /) : ");
ch = scan.next().charAt(0);

if(ch == '+')
{
res = a + b;
System.out.print("Result = " +res);
}
else if(ch == '-')
{
res = a - b;
System.out.print("Result = " +res);
}
else if(ch == '*')
{
res = a * b;
System.out.print("Result = " +res);
}
else if(ch == '/')
{
res = a / b;
System.out.print("Result = " +res);
}
else
{
System.out.print("Wrong Operator !!!");
}

}
}```

When the above Java Program is compile and executed, it will produce the following output:

Above Java Programming Example Output (for Addition):

Subtraction in Java

Above Java Programming Example Output (for Subtraction):

Multiplication in Java

Above Java Programming Example Output (for Multiplication):

Division in Java

Above Java Programming Example Output (for Division):

Same Program in Other Languages

You may also like to learn and practice the same program in other popular programming languages:

Tools
Calculator