How to make a calculator in Java

Java is a programming language widely used in various domains, including enterprise software development, web development, Android app development, scientific applications, and more.

Let's build a simple calculator in Java that can perform the following mathematical operations:

  • Addition

  • Subtraction

  • Multiplication

  • Division

Following is the coding example of a program written in java to perform the above mentioned mathematical operations.

Note: In the playground provided below, you are required to input two numbers followed by an arithmetic operation to be performed on those numbers. Please follow the format of entering the inputs as shown: "1 2 +".

Coding example

import java.io.*;
import java.lang.*;
import java.lang.Math;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args)
{
// Stores two numbers
double a, b;
// Take input from the user
Scanner scn = new Scanner(System.in);
System.out.println("Enter the numbers:");
// Take the inputs
a = scn.nextDouble();
b = scn.nextDouble();
System.out.println("Enter the arithmetic operator (+,-,*,/):");
char op = scn.next().charAt(0);
double output = 0;
switch (op) {
// case to add two numbers
case '+':
output = a + b;
break;
// case to subtract two numbers
case '-':
output = a - b;
break;
// case to multiply two numbers
case '*':
output = a * b;
break;
// case to divide two numbers
case '/':
output = a / b;
break;
default:
System.out.println("You enter wrong input");
}
System.out.println("Result:");
System.out.println(a + " " + op + " " + b + " = " + output);
}
}

Enter the input below

Explanation

  • Lines 10–19: The program starts by declaring variables a and b to store the two numbers that the user will input. It then prompts the user to enter the numbers using the Scanner class and the inputs are stored in a and b.

  • Lines 21–23: Next, the program prompts the user to enter an arithmetic operator (+, -, *, or /) to choose the desired operation. The operator input is stored in the variable op.

  • Lines 24–49: The program uses a switch statement to perform the selected arithmetic operation. Depending on the value of op, it adds (+), subtracts (-), multiplies (*), or divides (/) the numbers a and b. The result is stored in the variable output.

  • Lines 51–55: Finally, the program displays the final result by printing the original numbers a and b, the chosen operator op, and the calculated result output.

Following is the output of the above program.

Enter the numbers:
Enter the arithmetic operator (+,-,*,/):
Result:
1.0 + 2.0 = 3.0

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved