Java Calculator App

Su Suriya Ravichandran Updated 18 Nov 2026
14 min read ·Lesson 295 of 306

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)
OperatorName17 ? 5 with int17.0 ? 5 with double
+Addition2222.0
-Subtraction1212.0
*Multiplication8585.0
/Division3 (fraction dropped)3.4
%Remainder (modulo)22.0

How it works:

  • Dividing two int values gives an int, so 17 / 5 is 3, not 3.4. Casting one side with (double) a switches to decimal division.
  • The parentheses in (a + b) matter. Without them, " = " + a + b would join the text "17" and "5" into "175".
  • A calculator for users should work with double, so 7 / 2 gives 3.5 as 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 with yield.
  • With int, dividing by zero throws ArithmeticException automatically. With double, Java returns Infinity or NaN (not a number) instead, which is confusing for users. The explicit check throws a clear error.
  • default catches 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 that setScale added, so 19.000000 becomes 19.
  • toPlainString() avoids scientific notation. Plain toString() would print 1E+12 for one trillion.
  • 0.1 + 0.2 is stored as 0.30000000000000004 because double uses 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, and return leaves the method as soon as parsing succeeds. Invalid input never reaches the math.
  • nextLine() reads the whole line, then parseDouble converts it. This avoids the classic Scanner problem where nextDouble() leaves the Enter key in the buffer.
  • parseDouble always expects a dot as the decimal separator, so 3,5 is 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.
doubleBigDecimal
SpeedVery fastSlower
0.1 + 0.1 + 0.10.300000000000000040.30 (exact)
Operators+ - * /.add() .subtract() .multiply() .divide()
Division like 1 / 3Rounds silentlyNeeds a scale and RoundingMode
Best forScience, geometry, general calculatorsMoney, prices, tax, invoices

How it works:

  • Create BigDecimal from a string, new BigDecimal("0.10"). new BigDecimal(0.10) would copy the inexact binary value of the double.
  • divide(divisor, 2, RoundingMode.HALF_UP) keeps two decimal places, which is right for rupees and paise.
  • Without a scale, 1000 / 3 has infinitely many digits, so BigDecimal refuses 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:

  • DoubleBinaryOperator is a functional interface that takes two double values and returns a double. Each constant passes a lambda, and POWER passes the method reference Math::pow.
  • values() returns all constants in order, so fromSymbol can 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 switch on 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("0s+") splits on one or more spaces, so 12 + 7 and 12 + 7 both give three parts. Anything other than exactly three parts gets a usage message.
  • parseNumber accepts the word ans, which returns the previous result. This lets users chain calculations: 12 + 7, then ans * 2.
  • lastAnswer and history are updated only after apply succeeds. A failed division by zero leaves both unchanged.
  • history() returns List.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() returns false when 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() makes EXIT and Exit work 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 1 on 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:

  1. Clear responsibilities. Operation knows the math, Calculator parses and remembers, and CalculatorApp talks to the user. Each class can be changed or tested on its own.
  2. 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.
  3. Chained results. ans * 2 used the previous result 19, and the history shows 19 * 2 = 38 with the real value instead of the word ans.
  4. Readable output. 22 / 7 prints 3.142857, and 0.1 + 0.2 prints 0.3, thanks to the BigDecimal formatting step.
  5. Script friendly. In one-shot mode the * is quoted ('*') so the shell does not expand it into file names, and a failure returns exit code 1. 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Calculator App and get answers drawn from it.

Signed-in readers only.