Simple Calculator Using Switch in Java
Problem
A switch statement can branch on a single character just as easily as on an integer, making it a natural fit for dispatching on an arithmetic operator like +, -, *, or /.
Given two numbers and an operator symbol, compute the result of applying that operator.
Java Program
public class SimpleCalculatorSwitch {
public static void main(String[] args) {
double a = 12.0, b = 4.0;
char operator = '*';
double result;
switch (operator) {
case '+':
result = a + b;
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
default:
throw new IllegalArgumentException("Unknown operator: " + operator); // no break needed — throw exits immediately
}
System.out.println("Result: " + result);
}
}Output
Core Logic
Matching the operator character against each case label picks the right arithmetic operation without a chain of if/else comparisons.
- 1
switch (operator)compares the char against each case label in turn. - 2Each of
'+','-','*','/'computes its own result andbreaks immediately after. - 3The
defaultcase throws an exception for any operator that isn't one of the four recognized symbols.
operator = '*', the third case matches and computes 12.0 * 4.0 = 48.0.Key Point: Every case ends with break — without it, execution would fall through into the next case and silently compute the wrong operation.
Key Concepts
Approach 2: Java 8
import java.util.Map;
import java.util.function.DoubleBinaryOperator;
public class SimpleCalculatorMapLookup {
public static void main(String[] args) {
double a = 12.0, b = 4.0;
char operator = '*';
Map<Character, DoubleBinaryOperator> operations = Map.of( // pairs each operator with its lambda
'+', (x, y) -> x + y,
'-', (x, y) -> x - y,
'*', (x, y) -> x * y,
'/', (x, y) -> x / y
);
double result = operations.get(operator).applyAsDouble(a, b);
System.out.println("Result: " + result);
}
}
Output
Core Logic
A map from operator to operation replaces the switch entirely — looking up the right function and calling it does the same dispatch in one line.
- 1
Map.of(...)builds an immutable map pairing each operator character with aDoubleBinaryOperatorlambda. - 2
operations.get(operator)retrieves the lambda matching the given operator. - 3
.applyAsDouble(a, b)calls that lambda with both operands, producing the result directly.
operator = '*', the map returns the multiplication lambda, and calling it with 12.0, 4.0 gives 48.0.Key Point: Adding a new operator here means adding one more map entry, not another case block — the dispatch logic itself never changes.