Skip to lesson

Evaluating expressions

Compilers and interpreters evaluate math expressions using stacks. Postfix notation eliminates parentheses, while the shunting-yard algorithm converts standard infix notation into postfix.

Evaluating postfix (Reverse Polish) expressions

Postfix notation writes each operator after its operands (3 4 +), so no parentheses or precedence rules are needed to evaluate it.

Standard math notation is infix: 3 + 4. Postfix notation places operators after operands: 3 4 +. Infix requires parsing operator precedence and parentheses across multiple scanning passes. Postfix expressions have zero ambiguity and evaluate in a single linear O(n) pass.

  1. Token is a number: push onto the operand stack.
  2. Token is an operator: pop second operand b, then first operand a.
  3. Compute result = a op b.
  4. Push result back onto the operand stack.
  5. Return the final value remaining on the stack.

Example 1 · Postfix Expression Evaluator

PostfixEvaluatorDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
public class PostfixEvaluatorDemo {    public static int evaluatePostfix(String[] tokens) {        Deque<Integer> stack = new ArrayDeque<>();        for (String t : tokens) {            if (t.equals("+")) stack.push(stack.pop() + stack.pop());            else if (t.equals("*")) stack.push(stack.pop() * stack.pop());            else if (t.equals("-")) {                int b = stack.pop(), a = stack.pop();                stack.push(a - b);            } else if (t.equals("/")) {                int b = stack.pop(), a = stack.pop();                stack.push(a / b);            } else {                stack.push(Integer.parseInt(t));            }        }        return stack.pop();    }
    public static void main(String[] args) {        String[] expr = {"2", "1", "+", "3", "*"};        System.out.println("Result: " + evaluatePostfix(expr));    }}
Output
Result: 9

What this code does

  • 2 1 + evaluates to 3.
  • 3 3 * evaluates to 9.
  • The stack leaves the final answer 9 on top.

Scan the tokens from left to right. A number is pushed. An operator pops b first and then a, computes a op b and pushes the result back, so a - b and a / b keep the right order.

Trace on 2 1 + 3 *:

  • 2: push 2.
  • 1: push 1; stack [2, 1].
  • +: pop b = 1 and a = 2, compute 2 + 1 = 3 and push it; stack [3].
  • 3: push 3; stack [3, 3].
  • *: pop b = 3 and a = 3, compute 3 * 3 = 9 and push it.
  • The one number left, 9, is the answer.

Infix to postfix with the shunting-yard method

Dijkstra invented the shunting-yard algorithm to convert standard infix expressions into postfix notation. Operands go directly to the output string or queue. Operators wait on an operator stack until higher precedence operators finish. Parentheses enforce sub-expression grouping.

Example 2 · Infix to Postfix Shunting-Yard Converter

ShuntingYardDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
public class ShuntingYardDemo {    static int precedence(char op) {        if (op == '+' || op == '-') return 1;        if (op == '*' || op == '/') return 2;        return 0;    }
    public static String infixToPostfix(String s) {        StringBuilder out = new StringBuilder();        Deque<Character> ops = new ArrayDeque<>();
        for (char c : s.toCharArray()) {            if (Character.isDigit(c)) out.append(c).append(' ');            else if (c == '(') ops.push(c);            else if (c == ')') {                while (!ops.isEmpty() && ops.peek() != '(') out.append(ops.pop()).append(' ');                ops.pop();            } else if (c == '+' || c == '-' || c == '*' || c == '/') {                while (!ops.isEmpty() && precedence(ops.peek()) >= precedence(c)) {                    out.append(ops.pop()).append(' ');                }                ops.push(c);            }        }        while (!ops.isEmpty()) out.append(ops.pop()).append(' ');        return out.toString().trim();    }
    public static void main(String[] args) {        System.out.println(infixToPostfix("3+(4*2)"));    }}
Output
3 4 2 * +

What this code does

  • Digits 3, 4, 2 are written directly to output.
  • * has higher precedence and pops before +.
  • Output 3 4 2 * + accurately represents 3 + (4 * 2).

When an operator arrives, first pop every operator on the stack with higher or equal precedence to the output, then push the new one. A ( is pushed, and a ) pops operators to the output until the matching ( is removed. * and / have higher precedence than + and -.

Convert 3 + 4 * 2:

  • 3: an operand goes straight to the output [3].
  • +: the operator stack is [+].
  • 4: output [3, 4].
  • *: higher precedence than +, so push it; stack [+, *].
  • 2: output [3, 4, 2].
  • End of input: pop * then +, giving 3 4 2 * +.

Building a basic arithmetic calculator

A basic calculator evaluates expressions with addition, subtraction, multiplication, division, and parentheses.

Tokens can be processed on the fly using two stacks: an operand stack and an operator stack.

Example 3 · Basic Calculator with Parentheses

BasicCalculatorDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
public class BasicCalculatorDemo {    public static int calculate(String s) {        Deque<Integer> stack = new ArrayDeque<>();        int res = 0, num = 0, sign = 1;
        for (int i = 0; i < s.length(); i++) {            char c = s.charAt(i);            if (Character.isDigit(c)) {                num = num * 10 + (c - '0');            } else if (c == '+') {                res += sign * num;                num = 0;                sign = 1;            } else if (c == '-') {                res += sign * num;                num = 0;                sign = -1;            } else if (c == '(') {                stack.push(res);                stack.push(sign);                res = 0;                sign = 1;            } else if (c == ')') {                res += sign * num;                num = 0;                res *= stack.pop();                res += stack.pop();            }        }        return res + sign * num;    }
    public static void main(String[] args) {        System.out.println("Result: " + calculate("(1+(4+5+2)-3)+(6+8)"));    }}
Output
Result: 23

What this code does

  • Signs and running sums are pushed onto the stack when ( is entered.
  • Sub-results are computed and restored when ) is reached.
  • Computes nested arithmetic accurately in O(n) time.

Whenever a lower precedence operator arrives, execute pending operations immediately to keep space minimal.

Remember:

  • Two-stack model: numbers stack and operators stack.
  • Operator reduction: execute top operation before pushing lower precedence operator.
  • Whitespace trimming: ignore spaces during token parsing.

Next step

Check your understanding

10 quick questions