Java Calculator App
A Java calculator app is a classic beginner project that reads two numbers and an operator, does the math and prints the result. It is small enough to finish in one sitting, yet it uses most of the basics together: variables, operators, switch, methods, user input, exceptions, loops and enums. Building it well also teaches the edge cases real programs must handle, such as dividing by zero, invalid input and floating-point rounding.
This project continues from the Java Hello World App. You start with plain arithmetic and finish with calculator-app.jar, an interactive calculator with a prompt, error messages, a history list and an ans variable for the previous result. All examples were run on JDK 21.
Java Arithmetic Operators for a Calculator
Java has five arithmetic operators. The result depends on the types you use.
public class SimpleCalculator {
public static void main(String[] args) {
int a = 17;
int b = 5;
System.out.println(a + " + " + b + " = " + (a + b));
System.out.println(a + " - " + b + " = " + (a - b));
System.out.println(a + " * " + b + " = " + (a * b));
System.out.println(a + " / " + b + " = " + (a / b));
System.out.println(a + " % " + b + " = " + (a % b));
System.out.println(a + " / " + b + " = " + ((double) a / b) + " (decimal)");
}
}
17 + 5 = 22
17 - 5 = 12
17 * 5 = 85
17 / 5 = 3
17 % 5 = 2
17 / 5 = 3.4 (decimal)
| Operator | Name | 17 ? 5 with int | 17.0 ? 5 with double |
|---|---|---|---|
+ | Addition | 22 | 22.0 |
- | Subtraction | 12 | 12.0 |
* | Multiplication | 85 | 85.0 |
/ | Division | 3 (fraction dropped) | 3.4 |
% | Remainder (modulo) | 2 | 2.0 |
How it works:
- Dividing two
intvalues gives anint, so17 / 5is3, not3.4. Casting one side with(double) aswitches to decimal division. - The parentheses in
(a + b)matter. Without them," = " + a + bwould join the text"17"and"5"into"175". - A calculator for users should work with
double, so7 / 2gives3.5as people expect.
Choose the Operation With a switch Expression
A method that takes an operator character and returns the result keeps the math in one place. A switch expression maps each operator to its formula.
public class OperatorSwitch {
static double calculate(double left, char operator, double right) {
return switch (operator) {
case '+' -> left + right;
case '-' -> left - right;
case '*', 'x' -> left * right;
case '/' -> {
if (right == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
yield left / right;
}
case '%' -> left % right;
case '^' -> Math.pow(left, right);
default -> throw new IllegalArgumentException("Unknown operator: " + operator);
};
}
public static void main(String[] args) {
System.out.println(calculate(12, '+', 7.5));
System.out.println(calculate(9, 'x', 4));
System.out.println(calculate(2, '^', 10));
System.out.println(calculate(22, '/', 7));
try {
calculate(5, '/', 0);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
try {
calculate(5, '#', 2);
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
System.out.println(5.0 / 0 + " and " + 0.0 / 0 + " (what double division does without the check)");
}
}
19.5
36.0
1024.0
3.142857142857143
Error: Cannot divide by zero
Error: Unknown operator: #
Infinity and NaN (what double division does without the check)
How it works:
- Each
case ->returns a value directly.case '*', 'x'accepts both symbols for multiplication. - The division case needs more than one statement, so it uses a block
{ ... }and returns its value withyield. - With
int, dividing by zero throwsArithmeticExceptionautomatically. Withdouble, Java returnsInfinityorNaN(not a number) instead, which is confusing for users. The explicit check throws a clear error. defaultcatches any unknown operator, so the method never silently returns a wrong answer.
Format Calculator Results Without Extra Zeros
Users expect 19, not 19.0, and 3.142857, not 3.142857142857143. BigDecimal can round and strip trailing zeros in one chain.
import java.math.BigDecimal;
import java.math.RoundingMode;
public class FormatResult {
static String format(double value) {
if (Double.isNaN(value) || Double.isInfinite(value)) {
return String.valueOf(value);
}
return BigDecimal.valueOf(value)
.setScale(6, RoundingMode.HALF_UP) // at most 6 decimal places
.stripTrailingZeros() // 19.000000 -> 19
.toPlainString(); // never "1E+3"
}
public static void main(String[] args) {
double[] results = {19.0, 22.0 / 7, 0.1 + 0.2, 2.5, -40.0, 1024.0, 1e12};
for (double r : results) {
System.out.println(r + " -> " + format(r));
}
}
}
19.0 -> 19
3.142857142857143 -> 3.142857
0.30000000000000004 -> 0.3
2.5 -> 2.5
-40.0 -> -40
1024.0 -> 1024
1.0E12 -> 1000000000000
How it works:
setScale(6, RoundingMode.HALF_UP)rounds to six decimal places, the same way you learned at school (5 and above rounds up).stripTrailingZeros()removes the zeros thatsetScaleadded, so19.000000becomes19.toPlainString()avoids scientific notation. PlaintoString()would print1E+12for one trillion.0.1 + 0.2is stored as0.30000000000000004becausedoubleuses binary fractions. Rounding to six places hides that tiny error in the output.
Note: Rounding only changes what is displayed. For money, where every paisa must be exact, do the calculation itself with
BigDecimal, as shown later in this lesson.
Read Numbers Safely From the User
Double.parseDouble converts text to a number and throws NumberFormatException when the text is not a valid number. A loop asks again until the input is correct.
import java.util.Scanner;
public class ReadNumbers {
static double readNumber(Scanner scanner, String prompt) {
while (true) {
System.out.print(prompt);
String text = scanner.nextLine().strip();
try {
return Double.parseDouble(text);
} catch (NumberFormatException e) {
System.out.println(" '" + text + "' is not a number, try again.");
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double first = readNumber(scanner, "First number: ");
double second = readNumber(scanner, "Second number: ");
System.out.println("Sum = " + (first + second));
}
}
First number: twelve
'twelve' is not a number, try again.
First number: 12
Second number: 3,5
'3,5' is not a number, try again.
Second number: 3.5
Sum = 15.5
How it works:
while (true)repeats forever, andreturnleaves the method as soon as parsing succeeds. Invalid input never reaches the math.nextLine()reads the whole line, thenparseDoubleconverts it. This avoids the classicScannerproblem wherenextDouble()leaves the Enter key in the buffer.parseDoublealways expects a dot as the decimal separator, so3,5is rejected with a helpful message.
Use BigDecimal for Exact Money Calculations
A calculator for bills or prices must be exact. double cannot store values like 0.1 precisely, while BigDecimal stores decimal digits exactly.
import java.math.BigDecimal;
import java.math.RoundingMode;
public class MoneyMath {
public static void main(String[] args) {
// double cannot store 0.1 exactly
double price = 0.10;
double total = 0;
for (int i = 0; i < 3; i++) total += price;
System.out.println("double total = " + total);
// BigDecimal stores decimal digits exactly
BigDecimal exactPrice = new BigDecimal("0.10");
BigDecimal exactTotal = exactPrice.multiply(BigDecimal.valueOf(3));
System.out.println("BigDecimal total = " + exactTotal);
// division needs a scale and rounding mode
BigDecimal bill = new BigDecimal("1000.00");
BigDecimal perPerson = bill.divide(BigDecimal.valueOf(3), 2, RoundingMode.HALF_UP);
System.out.println("1000.00 / 3 = " + perPerson);
try {
bill.divide(BigDecimal.valueOf(3));
} catch (ArithmeticException e) {
System.out.println("Without scale : " + e.getMessage());
}
}
}
double total = 0.30000000000000004
BigDecimal total = 0.30
1000.00 / 3 = 333.33
Without scale : Non-terminating decimal expansion; no exact representable decimal result.
double | BigDecimal | |
|---|---|---|
| Speed | Very fast | Slower |
0.1 + 0.1 + 0.1 | 0.30000000000000004 | 0.30 (exact) |
| Operators | + - * / | .add() .subtract() .multiply() .divide() |
Division like 1 / 3 | Rounds silently | Needs a scale and RoundingMode |
| Best for | Science, geometry, general calculators | Money, prices, tax, invoices |
How it works:
- Create
BigDecimalfrom a string,new BigDecimal("0.10").new BigDecimal(0.10)would copy the inexact binary value of thedouble. divide(divisor, 2, RoundingMode.HALF_UP)keeps two decimal places, which is right for rupees and paise.- Without a scale,
1000 / 3has infinitely many digits, soBigDecimalrefuses with an exception instead of guessing.
Model Operators With an Enum
The final app stores its operators in an enum. Each constant carries its symbol and its formula as a lambda, so adding a new operator means adding one line.
package com.gocourse.calc;
import java.util.function.DoubleBinaryOperator;
/** The operators the calculator understands. */
public enum Operation {
ADD("+", (a, b) -> a + b),
SUBTRACT("-", (a, b) -> a - b),
MULTIPLY("*", (a, b) -> a * b),
DIVIDE("/", (a, b) -> {
if (b == 0) throw new ArithmeticException("Cannot divide by zero");
return a / b;
}),
MODULO("%", (a, b) -> {
if (b == 0) throw new ArithmeticException("Cannot take modulo by zero");
return a % b;
}),
POWER("^", Math::pow);
private final String symbol;
private final DoubleBinaryOperator formula;
Operation(String symbol, DoubleBinaryOperator formula) {
this.symbol = symbol;
this.formula = formula;
}
public String symbol() {
return symbol;
}
public double apply(double left, double right) {
return formula.applyAsDouble(left, right);
}
/** Finds the operation for a symbol such as "+", or throws if it is unknown. */
public static Operation fromSymbol(String symbol) {
for (Operation op : values()) {
if (op.symbol.equals(symbol)) return op;
}
throw new IllegalArgumentException("Unknown operator '" + symbol + "'. Use + - * / % ^");
}
}
How it works:
DoubleBinaryOperatoris a functional interface that takes twodoublevalues and returns adouble. Each constant passes a lambda, andPOWERpasses the method referenceMath::pow.values()returns all constants in order, sofromSymbolcan search them. The enum is the single source of truth for which operators exist.- Because the formulas live in the enum, the rest of the program never needs a long
switchon operator symbols.
Evaluate Expressions and Keep a History
The Calculator class parses a line such as 12 + 7, runs the operation, remembers the result as ans and records the history.
package com.gocourse.calc;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
/** Evaluates lines like "12 + 7" or "ans * 2" and remembers the history. */
public class Calculator {
private final List<String> history = new ArrayList<>();
private double lastAnswer = 0;
public double evaluate(String line) {
String[] parts = line.strip().split("\\s+");
if (parts.length != 3) {
throw new IllegalArgumentException("Write it as: number operator number, e.g. 12 + 7");
}
double left = parseNumber(parts[0]);
Operation operation = Operation.fromSymbol(parts[1]);
double right = parseNumber(parts[2]);
double result = operation.apply(left, right);
lastAnswer = result;
history.add(format(left) + " " + operation.symbol() + " " + format(right) + " = " + format(result));
return result;
}
private double parseNumber(String text) {
if (text.equalsIgnoreCase("ans")) return lastAnswer;
try {
return Double.parseDouble(text);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("'" + text + "' is not a number");
}
}
public List<String> history() {
return List.copyOf(history);
}
public static String format(double value) {
if (Double.isNaN(value) || Double.isInfinite(value)) return String.valueOf(value);
return BigDecimal.valueOf(value)
.setScale(6, RoundingMode.HALF_UP)
.stripTrailingZeros()
.toPlainString();
}
}
How it works:
split(" 0 s+")splits on one or more spaces, so12 + 7and12 + 7both give three parts. Anything other than exactly three parts gets a usage message.parseNumberaccepts the wordans, which returns the previous result. This lets users chain calculations:12 + 7, thenans * 2.lastAnswerandhistoryare updated only afterapplysucceeds. A failed division by zero leaves both unchanged.history()returnsList.copyOf(...), a read-only copy, so callers cannot edit or clear the calculator's internal list.
Build the Interactive Loop for the Java Calculator App
CalculatorApp shows a calc> prompt, handles commands and keeps running until the user types exit. It also supports a one-shot mode for scripts.
package com.gocourse.calc;
import java.util.List;
import java.util.Scanner;
/** Interactive calculator: java -jar calculator-app.jar, or pass one expression as arguments. */
public class CalculatorApp {
public static void main(String[] args) {
Calculator calculator = new Calculator();
// one-shot mode: java -jar calculator-app.jar 12 + 7
if (args.length > 0) {
try {
System.out.println(Calculator.format(calculator.evaluate(String.join(" ", args))));
} catch (RuntimeException e) {
System.err.println("Error: " + e.getMessage());
System.exit(1);
}
return;
}
System.out.println("GOCOURSE Calculator. Type 'help' for commands.");
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("calc> ");
if (!scanner.hasNextLine()) break; // Ctrl+D or end of piped input
String line = scanner.nextLine().strip();
switch (line.toLowerCase()) {
case "" -> { } // ignore empty lines
case "exit", "quit" -> {
System.out.println("Bye!");
return;
}
case "help" -> printHelp();
case "history" -> printHistory(calculator.history());
default -> {
try {
double result = calculator.evaluate(line);
System.out.println("= " + Calculator.format(result));
} catch (ArithmeticException | IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
}
}
private static void printHelp() {
System.out.println("""
Enter: number operator number (spaces required)
Operators: + - * / % ^
Use 'ans' for the previous result, e.g. ans * 2
Commands: history, help, exit""");
}
private static void printHistory(List<String> entries) {
if (entries.isEmpty()) {
System.out.println("No calculations yet.");
return;
}
for (int i = 0; i < entries.size(); i++) {
System.out.println((i + 1) + ". " + entries.get(i));
}
}
}
How it works:
- The
while (true)loop is a REPL (read, evaluate, print, loop).hasNextLine()returnsfalsewhen the input ends (Ctrl+D, or the end of a piped file), so the program exits cleanly instead of throwing an exception. - Commands are matched first, and anything else is treated as an expression.
line.toLowerCase()makesEXITandExitwork too. - The multi-catch
catch (ArithmeticException | IllegalArgumentException e)prints the error and continues the loop. One bad line never ends the session. - When arguments are given, the app evaluates them once and exits with code
1on error, which makes it usable in shell scripts.
Real-World Example: Package and Use calculator-app.jar
Compile the three classes and build an executable JAR, exactly as in the Hello World project.
calculator-app/
└── src/
└── com/
└── gocourse/
└── calc/
├── Calculator.java
├── CalculatorApp.java
└── Operation.java
cd calculator-app
javac -d out src/com/gocourse/calc/*.java
jar --create --file calculator-app.jar --main-class com.gocourse.calc.CalculatorApp -C out .
java -jar calculator-app.jar
An interactive session:
GOCOURSE Calculator. Type 'help' for commands.
calc> help
Enter: number operator number (spaces required)
Operators: + - * / % ^
Use 'ans' for the previous result, e.g. ans * 2
Commands: history, help, exit
calc> 12 + 7
= 19
calc> ans * 2
= 38
calc> 22 / 7
= 3.142857
calc> 2 ^ 10
= 1024
calc> 10 / 0
Error: Cannot divide by zero
calc> 5 # 2
Error: Unknown operator '#'. Use + - * / % ^
calc> ten + 1
Error: 'ten' is not a number
calc> 12+7
Error: Write it as: number operator number, e.g. 12 + 7
calc> 0.1 + 0.2
= 0.3
calc> history
1. 12 + 7 = 19
2. 19 * 2 = 38
3. 22 / 7 = 3.142857
4. 2 ^ 10 = 1024
5. 0.1 + 0.2 = 0.3
calc> exit
Bye!
One-shot mode for scripts, here adding 18% GST to a price:
java -jar calculator-app.jar 250 '*' 1.18
java -jar calculator-app.jar 9 / 0; echo "exit code: $?"
295
Error: Cannot divide by zero
exit code: 1
How it works:
- Clear responsibilities.
Operationknows the math,Calculatorparses and remembers, andCalculatorApptalks to the user. Each class can be changed or tested on its own. - Every error is handled. Division by zero, unknown operators, words instead of numbers and missing spaces each produce a specific message, and the prompt returns so the user can try again.
- Chained results.
ans * 2used the previous result19, and the history shows19 * 2 = 38with the real value instead of the wordans. - Readable output.
22 / 7prints3.142857, and0.1 + 0.2prints0.3, thanks to theBigDecimalformatting step. - Script friendly. In one-shot mode the
*is quoted ('*') so the shell does not expand it into file names, and a failure returns exit code1. The JAR can be copied to a server and run as described in Java JAR Deployment.
The next project, the Java Number Guess Game, uses the same loop-and-validate pattern together with random numbers.