You build a Java scientific calculator by separating four concerns: a tokenizer that turns the typed expression into numbers, names, and operators; a parser that respects precedence and parentheses; an evaluator that computes trigonometric, logarithmic, exponential, and root functions; and a thin interface layer, either Swing or a console loop, that only passes text in and results out. The single most important design decision comes first: do not evaluate keystroke by keystroke. Parse the full expression into a structure before computing, because that is what makes precedence, unary minus, and functions like sin(30) behave correctly.
This guide targets Java 17 or newer (any version from 11 up works), assumes you can compile a single file or a small Maven project, and stays inside the standard library: java.util, java.lang.Math, javax.swing for the optional desktop shell. No third-party math libraries are needed. Everything below builds a working calculator in four stages, each one runnable and testable before you start the next.
Why a parser beats chained button presses
The naive calculator design stores a running total and applies each operator as it's pressed. That works for 2 + 3 = and collapses the moment a user types 2 + 3 × 4. If you apply operators left to right, you get 20; the correct answer is 14. Scientific calculators make this worse by adding parentheses, functions, powers, and unary signs, all of which interact.
The fix is the standard two-step approach used by real expression evaluators. First, convert the input string into postfix (reverse Polish) notation with the shunting-yard algorithm, which handles precedence and parentheses in one pass. Second, evaluate the postfix queue with a stack. Alternatively, write a small recursive-descent parser that computes directly; it's fewer lines and easier to debug with a debugger, but shunting-yard generalizes more cleanly if you later add variables or user-defined functions.
Both approaches need a tokenizer first, and both need a function layer that isolates Math calls behind a name lookup. That separation is what lets you swap a Swing JTextField for a console Scanner without touching the math.
| Layer | Input | Output | Failure it prevents |
|---|---|---|---|
| Tokenizer | "sin(30)+2^3" | [FUNC sin, LPAREN, NUM 30, RPAREN, PLUS, NUM 2, POW, NUM 3] | Garbled multi-character numbers, unknown symbols |
| Parser | token list | postfix queue or AST | Wrong precedence, unmatched parentheses |
| Evaluator | postfix queue | double result | Stack underflow, division by zero surfacing silently |
| UI | user text | formatted string | Mixing display logic into math logic |
Stage 1: Set up the project and the math contract
Before writing the tokenizer, decide what "scientific" means for your build. A practical baseline includes: + - * /, ^ for power, unary minus, parentheses, the constants pi and e, and the functions sin cos tan asin acos atan ln log sqrt abs exp. That set is testable in an afternoon and covers the overwhelming majority of real use.
Create a Maven project or a plain folder with Calculator.java. If you use Maven, set the compiler to release 17 in pom.xml; if you use the command line, javac Calculator.java and java Calculator are enough for a single-file build. Pin the JDK version in your build file rather than relying on whatever is installed, because Math results are stable across versions but your team's machines may not be.
Now write the function layer as a single lookup. This is the contract everything else depends on:
The degree-versus-radian choice is the first place scientific calculators diverge, and it's a decision you must make explicitly. Java's Math.sin takes radians. If your calculator displays sin(30) and returns -0.988, you forgot the conversion. The code above converts input to radians for the trig functions and converts inverse-trig output back to degrees, which matches what most handheld scientific calculators do in their default mode. If you'd rather expose radians, drop the toRadians and toDegrees calls and label the mode in the UI. Don't do both without a visible toggle, or users will distrust every result.
Success check for this stage: write a tiny main that prints applyFunction("sin", 30) and confirm you get 0.49999999999999994 rather than -0.988. The tiny floating-point error is normal and expected; see the formatting section later.
Stage 2: Tokenize the input string
A tokenizer scans left to right and emits typed tokens. The tricky parts are multi-digit numbers with decimals, multi-letter function names, and deciding what counts as an error.
Work through the string character by character:
1: Skip whitespace. 2: If the character is a digit or a decimal point, consume the longest run of digits and at most one decimal point, then emit a NUMBER token parsed with Double.parseDouble. 3: If the character is a letter, consume the longest run of letters (or digits after the first letter, if you want log2 later). Emit CONSTANT for pi and e, FUNCTION for known names, and throw for anything else. 4: If the character is one of + - * / ^ ( ), emit the corresponding operator or parenthesis token. 5: Anything else is an error with the character position included in the message.
The word-boundary rule is where naive tokenizers break. If you scan letters greedily, sin(30) yields sin correctly, but e inside a number like 1e-3 would confuse a simple scanner. For a first version, either reject scientific notation input or handle it explicitly inside the number scanner: after the digits, if the next character is e or E and the one after is a digit or sign-plus-digit, consume the exponent as part of the number. Decide once and document it, because 1e-3 parsed as a number and e parsed as Euler's constant lead to wildly different answers.
Represent tokens as a small record:
The tokenizer returns a List. A useful check at this stage is round-tripping: print the token list for "-2.5 + sin(pi/2)^2" and confirm it reads as unary-minus handling will expect. Notice that the leading - arrives as an operator token with no operand before it; the parser, not the tokenizer, decides it's unary.
One common failure: 2(3+4) with implicit multiplication. Most simple parsers reject it, and that's acceptable if your error message says "unexpected (" rather than crashing. Adding implicit multiplication means inserting a * token whenever a number or ) is immediately followed by a number, (, or function name, which is a small refinement you can add later without changing the rest of the pipeline.
Stage 3: Parse with precedence and parentheses
Use the shunting-yard algorithm to convert the token list to postfix. The rules, stated plainly so you can implement them without a reference:
Numbers and constants go straight to the output queue. Functions go on the operator stack. An operator o1 pops operators from the stack to the output while the stack top is an operator o2 with higher precedence, or equal precedence and o1 is left-associative. Then o1 is pushed. A left parenthesis is pushed. A right parenthesis pops to the output until a left parenthesis appears, discards that parenthesis, and if the new stack top is a function, pops it to the output. At the end, pop everything remaining to the output.
Set precedence as ^ highest and right-associative, then unary minus, then * /, then + -. Model unary minus as a distinct operator token emitted by the parser when a - appears where an operand is expected—at the start, after another operator, or after (. Treating it as ordinary subtraction is the classic bug that makes -3^2 return 9 instead of -9, because ^ binds tighter than unary minus in standard math notation: -3^2 means -(3^2). If you want the affected behavior, decide deliberately and note it; silently getting one or the other is what erodes trust in the tool.
In Java, the operator stack can be a Deque used with push/pop. Guard against popping an empty stack, which in postfix evaluation later manifests as stack underflow; catching it in the parser with a message like "misplaced operator at position 4" is far more useful to users than a raw NoSuchElementException.
Worked trace for 2 + 3 * 4:
Output: 2, stack: empty. Output: 2, stack: +. Output: 2 3, stack: + * after pushing * because it outranks +. Output: 2 3 4, then end-of-input pops * then +, giving 2 3 4 * +. Evaluation: 3 * 4 = 12, then 2 + 12 = 14.
For sin(30) + 1: sin is pushed, ( is pushed, 30 goes to output, ) pops nothing (stack top is (), discards the paren, then pops sin to output. The queue reads 30 sin 1 +, and evaluation gives 0.5 + 1 = 1.5 in degree mode.
Success check for this stage: assert that 2+3*4 yields 14, (2+3)*4 yields 20, 2^3^2 yields 512 (right-associative), and -3^2 yields -9. If your ^ is left-associative you'll get 64 for the third case and 9 for the fourth—both wrong under standard convention.
Stage 4: Evaluate the postfix queue safely
The evaluator walks the postfix list. Numbers push onto a Deque. Binary operators pop two values (the right operand first), compute, and push. Unary operators and functions pop one. At the end, exactly one value should remain; if more or fewer do, the expression was malformed.
Two failure modes deserve explicit handling because they are common and confusing:
Division by zero. Java's double division returns Infinity or NaN rather than throwing, so 1/0 silently becomes Infinity and poisons downstream arithmetic. Decide whether to allow it (many scientific calculators show Infinity or an error) and, if you show it, label it clearly. If you'd rather reject it, check the divisor before dividing and throw a CalculatorException with a readable message.
Domain errors. Math.log(-1) returns NaN, Math.sqrt(-1) returns NaN, and Math.asin(2) returns NaN. These don't throw, so a calculator that returns NaN to the screen looks broken. Either propagate NaN with a visible "undefined" label, or wrap each function with a domain check and produce a specific error like "logarithm requires a positive argument." The second is more work but far friendlier.
Wrap the whole pipeline in one exception type so the UI has a single catch:
A subtlety for power and roots: negative bases with fractional exponents produce NaN through Math.pow, as in (-8)^(1/3), which is arguably -2 in real-number terms but Math.pow returns NaN because of how it handles the fractional exponent. If cube roots of negatives matter to your users, special-case fractional exponents with odd denominators, or document the limitation plainly.
Testing at this stage should be mechanical: a table of expression/expected pairs, run in a loop, failing loudly with the expression that broke. Include 2+2, (1+2)3, sin(30), cos(60), 2^10, sqrt(144), ln(e), log(1000), -5+2, 3-2, and one malformed input like 2++. Ten tests catch the vast majority of parser and evaluator bugs before a UI ever touches them.
Stage 5: Format results so they look right
Raw double output is a usability problem: sin(30) prints 0.49999999999999994, and 0.1+0.2 prints 0.30000000000000004. These are correct binary floating-point results, not bugs, but users read them as errors.
Format with BigDecimal rounding to a fixed number of significant digits (12 is a good default for double precision), then strip trailing zeros:
This turns 0.49999999999999994 into 0.5 and 0.30000000000000004 into 0.3, which is what a calculator should show. Keep the full-precision value in memory and format only for display; rounding at every step would accumulate error. Watch toPlainString versus toString on BigDecimal: toString can produce scientific notation like 1E+3, which is fine for huge numbers but surprising for 1000.
For very large or very small magnitudes, switch to scientific notation explicitly when the absolute value is at or above 1e12 or below 1e-9. Pick those thresholds once, put them in named constants, and use them consistently—otherwise the same number displays differently depending on the path that produced it.
Stage 6: Put a Swing or console front end on it
The UI does one job: collect a string, call evaluate, and show the formatted result or the error message. Keep every bit of parsing out of the event handler.
For Swing, a JFrame with a JTextField for the expression, a JLabel or a read-only field for the result, and a grid of JButtons that append characters to the expression field is enough. Wire the = button and the Enter key to the same method, which catches CalculatorException and any other RuntimeException from the pipeline, then writes the message into the result field:
Build the panel grid with a loop over button labels rather than twenty manual new JButton calls; the loop keeps the layout and the label list in lockstep. Call SwingUtilities.invokeLater to construct the frame on the event dispatch thread, which is the standard thread-safety requirement for Swing. If you want a degree/radian toggle, make it a JComboBox or a pair of radio buttons that changes a field the function layer reads—one visible control, one underlying mode.
For a console version, a Scanner loop is useful during development and for scripted tests:
The console shell is the fastest way to stress-test the engine: paste fifty expressions, confirm each result against a known-good reference, and fix the parser before you invest in buttons.
Stage 7: Test edge cases, then harden
A calculator's trustworthiness comes from its failure behavior, not its happy path. Check each of these deliberately, with the expression and the correct response:
Unbalanced parentheses. 2*(3+4 should yield an error naming the missing parenthesis, not a NoSuchElementException stack trace. Same for 2+3).
Empty or whitespace input. Pressing = on an empty field should produce "empty expression," because an empty postfix queue fails the exactly-one-value check.
Dangling operators. 5 + and * 3 should be rejected with a message pointing at the operator, not a stack-underflow crash.
Unary minus in compound positions. 3 * -2 should be -6; -(-3) should be 3; 2--3 should be 5 in most conventions. Verify each against your parser's unary rule.
Function without parentheses. sin 30 needs a defined behavior. Simplest is to require parentheses and say so in the error message; the alternative, implicit function application, complicates precedence for little benefit.
Huge and tiny values. 2^1000 is about 1.07e301, near the edge of double's range; 2^1024 overflows to Infinity. Confirm format labels it as such instead of printing a nonsense number.
Precision-sensitive comparisons. sin(180) in degree mode comes out around 1.22e-16, not zero, because Math.toRadians(180) isn't exactly π. If you want sin(180) to display 0, either round near-zero results (careful: this hides real small answers) or use a display threshold and document it.
When further work needs a professional: if you're extending this into a tool for regulated numerical reporting—tax, structural load calculations, clinical dosing—stop and have the formulas reviewed by a qualified domain expert and validated against a certified reference, because a floating-point edge case there is a correctness and liability problem, not a usability one. For classroom, hobby, or utility work, the pipeline above with a solid test table is the right scope.
Common pitfalls that cost the most time
Several mistakes account for most debugging hours in calculator projects, and most have a one-line preventable fix.
Applying operators as they're typed. This is the root failure described earlier; parse first, compute second, every time.
Confusing radians and degrees silently. Pick a mode, display it in the UI, and convert in exactly one place. Double conversion—toRadians inside the function layer and again in the caller—turns sin(30) into nonsense.
Letting NaN reach the screen. Banking on "the user will know what NaN means" is optimistic; label it "undefined" and, where cheap, say why.
Rounding on every operation. Round for display only. Keep double intermediates; if you need decimal-exact arithmetic, that's a different project with BigDecimal throughout and different performance and API trade-offs.
Ignoring locale. Double.parseDouble always expects a period as the decimal separator, so a user whose keyboard produces 1,5 gets a parse error. If you ship outside the US, either normalize commas to periods at the tokenizer with an explicit rule or handle NumberFormat locale-aware parsing—but decide, because inconsistent input handling is worse than a documented limitation.
Growing a switch a hundred cases long. The function table is fine as a switch for twelve functions; past that, move to a Map<String, DoubleUnaryOperator> and look up by name. Same behavior, easier to extend and test in isolation.
What to add after the core works
Once the four-stage pipeline is tested and the UI shows correct results, useful extensions arrange themselves in rough order of value per hour invested. A degree/radian toggle with a visible indicator is the highest-value addition. Memory keys (M+, MR, MC) are trivial to bolt onto the UI layer and match user expectations from physical calculators. Expression history—keeping the last twenty expressions and results in a list—costs little and helps users check their own work.
A backspace-and-clear button set, keyboard focus on the expression field at startup, and an answer key (ans) that refers to the previous result all come next. Variable support and user-defined functions require more parser work, because you need a symbol table and a way to bind arguments; do that only if the use case demands it, and keep it behind the same tokenizer and parser so your existing tests keep passing.
What you shouldn't add early is a graphing canvas or arbitrary-precision arithmetic. Both are substantial projects layered on a working core, and building them before your expression engine is trustworthy multiplies the debugging surface. Get 2 + 3 * 4 right, then sin(30), then everything else.
The test to run before calling the project done is a single scripted session: eight or ten expressions covering precedence, parentheses, unary minus, each trig function in your chosen mode, a logarithm, a power with a negative exponent, and three malformed inputs, each matched against a reference value or a required error message. If those pass, you have a scientific calculator that behaves predictably, and the maintainable structure to extend it.