Wednesday, October 22, 2025
HomeLanguagesJavaBasic Calculator Program Using Java

Basic Calculator Program Using Java

Create a simple calculator which can perform basic arithmetic operations like addition, subtraction, multiplication, or division depending upon the user input.

Example:

Enter the numbers: 
2 
2

Enter the operator (+,-,*,/)
+
The final result:
2.0 + 2.0 = 4.0

Approach

  • Take two numbers using the Scanner class. The switch case branching is used to execute a particular section.
  • Using a switch case to evaluate respective operations.

Below is the Java program to implement the calculator:

Java




// Java program for simple calculator
import java.io.*;
import java.lang.*;
import java.lang.Math;
import java.util.Scanner;
 
// Driver class
public class BasicCalculator {
    // main function
    public static void main(String[] args)
    {
        // Stores two numbers
        double num1, num2;
 
        // Take input from the user
        Scanner sc = new Scanner(System.in);
 
        System.out.println("Enter the numbers:");
 
        // Take the inputs
        num1 = sc.nextDouble();
        num2 = sc.nextDouble();
 
        System.out.println("Enter the operator (+,-,*,/):");
 
        char op = sc.next().charAt(0);
        double o = 0;
 
        switch (op) {
        // case to add two numbers
        case '+':
            o = num1 + num2;
            break;
 
        // case to subtract two numbers
        case '-':
            o = num1 - num2;
            break;
 
        // case to multiply two numbers
        case '*':
            o = num1 * num2;
            break;
 
        // case to divide two numbers
        case '/':
            o = num1 / num2;
            break;
 
        default:
            System.out.println("You enter wrong input");
        }
 
        System.out.println("The final result:");
        System.out.println();
 
        // print the final result
        System.out.println(num1 + " " + op + " " + num2
                           + " = " + o);
    }
}


Output:

Enter the numbers:
2
2
Enter the operator (+,-,*,/)
+
The final result:
2.0 + 2.0 = 4.0

Time Complexity: O(1)

Auxiliary Space: O(1)

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS