Simple Calculator Program in Java Using Switch

In this tutorial, we will learn how to build a simple calculator program in Java that performs basic arithmetic operations: addition, subtraction, multiplication, and division.

Building a simple calculator is one of the best beginner-level projects when learning Java programming. It helps you understand important Java concepts such as methods, switch statements, user input handling (Scanner), conditional statements, and arithmetic operators.

We will explore different methods to create a simple calculator in Java. So, let’s understand the first method.

Java Program to Build Simple Calculator Using Switch

Let’s write a Java program to create a simple calculator that accepts two numbers and performs arithmetic operations, such as addition, subtraction, multiplication, and division.

In this approach, we will use a switch statement and separate methods for each arithmetic operation.

Complete Java Program

import java.util.Scanner;
public class SimpleCalculator {

    // Declare a static method that accepts two double values as arguments, add them and returns the result.
    public static double add(double a, double b) {
        return a + b;
    }

    // This method subtracts the second number from the first number and returns the result. 
    public static double subtract(double a, double b) {
        return a - b;
    }

    // Declare a method for multiplication that multiplies two numbers and returns their product.
    public static double multiply(double a, double b) {
        return a * b;
    }

    // This method performs the division operation with zero check.
    public static double divide(double a, double b) {
        if (b == 0) {
            System.out.println("Error: Division by zero is not allowed.");
            return 0;
        }
        return a / b;
    }

    public static void main(String[] args) {
        // Create a Scanner class object to read input from the keyword.
        Scanner scanner = new Scanner(System.in);
        
        // Declare four variables.
        double num1, num2, result;
        char operator;

        System.out.println("=== Welcome to the Java Simple Calculator ===");
        System.out.print("Enter the first number: ");
        num1 = scanner.nextDouble();

        System.out.print("Enter an operator (+, -, *, /): ");
        // The next().charAt(0) reads the operator entered by the user and extracts its first character.
        operator = scanner.next().charAt(0);

        System.out.print("Enter the second number: ");
        num2 = scanner.nextDouble();

        boolean validOperation = true;

        // Switch statement to evaluate the operator
        switch (operator) {
            case '+':
                result = add(num1, num2);
                break;
            case '-':
                result = subtract(num1, num2);
                break;
            case '*':
                result = multiply(num1, num2);
                break;
            case '/':
                if (num2 != 0) {
                    result = divide(num1, num2);
                } else {
                    validOperation = false;
                    result = 0;
                }
                break;
            default:
                System.out.println("Error: Invalid operator entered!");
                validOperation = false;
                result = 0;
                break;
        }

        // Display the result if the operation was valid
        if (validOperation) {
            System.out.println("Result: " + num1 + " " + operator + " " + num2 + " = " + result);
        }

        scanner.close();
    }
}

Output 1:

=== Welcome to the Java Simple Calculator ===
Enter the first number: 25.5
Enter an operator (+, -, *, /): +
Enter the second number: 14.5
Result: 25.5 + 14.5 = 40.0

Output 2:

=== Welcome to the Java Simple Calculator ===
Enter the first number: 50
Enter an operator (+, -, *, /): /
Enter the second number: 0
Error: Division by zero is not allowed.

In this program:

  • We import java.util.Scanner to capture user input from the console.
  • The Scanner class belongs to the java.util package. It allows us to accept input from the keyboard.
  • The following methods are used to read different types of input:
    • nextDouble(): Reads a double value from the user.
    • next(): Reads a token as a string.
    • charAt(0): Extracts the first character from the entered string.
  • We declare four variables named num1, num2, result, and operator.
    • num1: Stores the first number entered by the user.
    • num2: Stores the second number entered by the user.
    • result: Stores the result of the arithmetic operation.
    • operator: Stores the arithmetic operator entered by the user.
  • We use the double data type because it supports both whole numbers and decimal values.
  • Instead of writing all calculation logic inside the main method, we create dedicated static methods for addition, subtraction, multiplication, and division. This promotes reusability, clean code structure, and maintainability.
  • The switch (operator) block checks which character the user entered (+, -, *, or /) and routes execution to the appropriate method. If an unsupported operator is provided, the default case catches it and notifies the user.
  • The break statement terminates the switch case and prevents execution from continuing into subsequent cases.
  • Division by zero throws an ArithmeticException or yields Infinity in floating-point math. Our code explicitly checks if the second number is 0 before performing division to prevent unexpected application crashes.
  • Finally, we close the Scanner object after accepting the required input. This helps release the resources associated with it.

Java Calculator Program Using Methods Without Return Values

Alternatively, we can build a simple calculator using void methods that do not return a value. In this approach, each method handles the calculation and prints the result directly to the console.

Complete Java Program

import java.util.Scanner;
public class Calculator {

    // Method to perform addition and print the result directly
    public static void add(double a, double b) {
        System.out.println("Result = " + (a + b));
    }
    // Method to perform subtraction and print the result directly
    public static void subtract(double a, double b) {
        System.out.println("Result = " + (a - b));
    }
    // Method to perform multiplication and print the result directly
    public static void multiply(double a, double b) {
        System.out.println("Result = " + (a * b));
    }
    // Method to perform division with a zero check and print the result directly
    public static void divide(double a, double b) {
        if (b != 0) {
            System.out.println("Result = " + (a / b));
        } else {
            System.out.println("Error: Division by zero is not allowed.");
        }
    }
    public static void main(String[] args) {
        // Create a Scanner object to read user input from the console
        Scanner sc = new Scanner(System.in);

        // Prompt the user to enter the first number
        System.out.print("Enter the first number: ");
        double num1 = sc.nextDouble();

        // Prompt the user to enter a valid mathematical operator
        System.out.print("Enter an operator (+, -, *, /): ");
        char operator = sc.next().charAt(0);

        // Prompt the user to enter the second number
        System.out.print("Enter the second number: ");
        double num2 = sc.nextDouble();

        // Use a switch statement to route execution to the correct operation method
        switch (operator) {
            case '+':
                add(num1, num2);
                break;

            case '-':
                subtract(num1, num2);
                break;

            case '*':
                multiply(num1, num2);
                break;

            case '/':
                divide(num1, num2);
                break;

            default:
                // Handle cases where the user enters an unsupported operator
                System.out.println("Invalid operator!");
        }

        // Close the scanner object to free up system resources
        sc.close();
    }
}

Output:

Enter the first number: 25
Enter an operator (+, -, *, /): *
Enter the second number: 4
Result = 100.0

Calculator Program in Java Using Modern Switch

Let’s write a Java program to build a simple calculator using the modern switch statement. The modern switch syntax uses the arrow (->) operator, which eliminates the need for break statements and allows the switch block to return a value directly.

Complete Java Code

import java.util.Scanner;
/**
 * CalculatorEngine handles the core mathematical logic 
 * using Java's modern switch expression (Java 14+).
 */
class CalculatorEngine {
    
    // Method to perform calculations based on the operator
    public static double calculate(double num1, double num2, char operator) {
        // Modern switch expression returning the calculated value directly without break statements.
        return switch (operator) {
            case '+' -> num1 + num2;
            case '-' -> num1 - num2;
            case '*' -> num1 * num2;
            case '/' -> {
                // Check for division by zero before yielding the result.
                if (num2 == 0) {
                    throw new ArithmeticException("Division by zero is not allowed.");
                }
                yield num1 / num2;
            }
            default -> throw new IllegalArgumentException("Invalid operator entered!");
        };
    }
}

public class Main {
    public static void main(String[] args) {
        // Create a Scanner object to capture console inputs.
        Scanner scanner = new Scanner(System.in);
        System.out.println("=== Welcome to the Modern Java Calculator ===");

        // Prompt and read the first number.
        System.out.print("Enter the first number: ");
        double num1 = scanner.nextDouble();

        // Prompt and read the arithmetic operator (+, -, *, /).
        System.out.print("Enter an operator (+, -, *, /): ");
        char operator = scanner.next().charAt(0);

        // Prompt and read the second number.
        System.out.print("Enter the second number: ");
        double num2 = scanner.nextDouble();

        try {
            // Delegate the calculation to the separate CalculatorEngine class.
            double result = CalculatorEngine.calculate(num1, num2, operator);

            // Display the final calculation result if successful.
            System.out.println("Result: " + num1 + " " + operator + " " + num2 + " = " + result);

        } catch (ArithmeticException | IllegalArgumentException e) {
            // Catch and display error messages for division by zero or invalid operators.
            System.out.println("Error: " + e.getMessage());
        } finally {
            // Close the scanner object to free up system resources.
            scanner.close();
        }
    }
}

Expected Output 1: Successful Addition

=== Welcome to the Modern Java Calculator ===
Enter first number: 45.5
Enter an operator (+, -, *, /): +
Enter second number: 10.5
Result: 45.5 + 10.5 = 56.0

Expected Output 2: Division by Zero Error Handling

=== Welcome to the Modern Java Calculator ===
Enter first number: 100
Enter an operator (+, -, *, /): /
Enter second number: 0
Error: Division by zero is not allowed.

In this program:

  • Arrow Operator (->): Each case maps directly to an expression or block. Only the matched branch executes, meaning no break statements are required, eliminating common fall-through bugs.
  • Switch as an Expression: The entire switch block evaluates and returns a value directly into the result variable, keeping your code concise and functional.
  • Yield Keyword: When a case requires multiple lines of logic (like validating division by zero), you wrap the code in curly braces {} and use yield to return the value for that branch.

Java Calculator Program Using If-Else Ladder

Let’s write a Java program to build a simple calculator using the if-else ladder to evaluate operators or menu selections.

Complete Java Program

import java.util.Scanner;
public class CalculatorUsingIfElse {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the first number: ");
        double num1 = scanner.nextDouble();

        System.out.print("Enter an operator (+, -, *, /): ");
        char operator = scanner.next().charAt(0);

        System.out.print("Enter the second number: ");
        double num2 = scanner.nextDouble();
        double result;

        if (operator == '+') {
            result = num1 + num2;
            System.out.println("Result: " + result);
        } else if (operator == '-') {
            result = num1 - num2;
            System.out.println("Result: " + result);
        } else if (operator == '*') {
            result = num1 * num2;
            System.out.println("Result: " + result);
        } else if (operator == '/') {
            if (num2 != 0) {
                result = num1 / num2;
                System.out.println("Result: " + result);
            } else {
                System.out.println("Error: Division by zero!");
            }
        } else {
            System.out.println("Error: Invalid operator!");
        }

        scanner.close();
    }
}

Expected Output:

Enter the first number: 30
Enter an operator (+, -, *, /): *
Enter the second number: 10
Result: 300.0

Conclusion

In this tutorial, we explored how to build a simple calculator in Java using modern switch expressions and various structural approaches. We covered how to capture user input using the Scanner class, implement clean error handling, and perform fundamental arithmetic operations like addition, subtraction, multiplication, and division.

DEEPAK GUPTA

DEEPAK GUPTA

Deepak Gupta is the Founder of Scientech Easy, a Full Stack Developer, and a passionate coding educator with 8+ years of professional experience in Java, Python, web development, and core computer science subjects. With strong expertise in full-stack development, he provides hands-on training in programming languages and in-demand technologies at the Scientech Easy Institute, Dhanbad.

He regularly publishes in-depth tutorials, practical coding examples, and high-quality learning resources for both beginners and working professionals. Every article is carefully researched, technically reviewed, and regularly updated to ensure accuracy, clarity, and real-world relevance, helping learners build job-ready skills with confidence.