Chapter 6 · Simulation

Expression Evaluator

← Chapter 6
QUESTION

NOW

    Expression Evaluator

    Goal: See step by step how the value of a Java expression is found. Java first builds the expression tree according to operator precedence, then evaluates the operands from left to right.

    How to use it

    1. Pick a ready-made example, or type your own expression in the box and press Evaluate.
    2. Step ▶ reduces one sub-expression at a time; the highlighted part is what will be computed in the next step. Play advances the steps automatically, Back goes back one step. The → / ← keys work too.
    3. In the tree, each node shows its computed value and type (int / double) below it.
    4. In Try it yourself mode, predict the output of System.out.println(expression): double results are printed like 7.0; if it will throw an exception, type error.

    Summary of the rules

    • Precedence: postfix x++ → prefix ++x, unary -, explicit cast (double) → * / % → + -. Left to right at the same precedence.
    • Between two int values, / is integer division: the fractional part is discarded (17 / 5 → 3). % gives the remainder, and its sign is the sign of the dividend.
    • If one operand is a double, the other is also promoted to double by type promotion (7 / 2.0 → 3.5).
    • (double) 7 / 2 casts first (3.5); (double) (7 / 2) divides first (3.0).
    • x++ yields the old value and then increments; ++x increments first and yields the new value.
    • Division by zero in int division throws an ArithmeticException; in double division the result is Infinity or NaN. int overflow silently wraps around.

    Related slides: Chapter 6 · Variables, Data Types and Operators.