AP® Computer Science A · Unit 1 · Topic 1.3

Arithmetic Expressions and Operator Precedence

Java evaluates expressions using operator precedence, not reading order: multiplication and division fire before addition and subtraction, collapsing the expression one operator at a time until a single value remains.

Java does not read an expression left to right and compute as it goes. It follows a fixed precedence order, the same one you learned as order of operations in math class. Multiplication and division outrank addition and subtraction, so every·and / in the expression fires before any + or - does, no matter where it sits in the line. Within the same precedence level, Java works left to right. Parentheses override all of this: whatever sits inside them gets evaluated first, as its own mini-expression, before the result gets folded back into the rest of the line.

Picture the expression collapsing in rounds. Java scans for the highest-precedence operator, computes it, and replaces that piece with its answer, shrinking the expression by one operator each time. It repeats this until one value is left. This matters because a method call like System.out.println(2 + 3·4) does not know or care about precedence itself; it just receives whatever single value the expression collapses down to. Get the order wrong and you hand the method the wrong value, even though every digit and operator you typed was correct.

This sits right underneath variables and assignment: once you know a variable holds a value sitting in memory, arithmetic expressions are how you combine several of those values into one new value, often to store back into a variable or pass into a method. The next topic, compound assignment and casting, builds directly on this collapsing process, since those operators also rely on precedence to decide what gets computed before the result is stored or converted.

Key terms

operator precedence
The fixed ranking that decides which operator in an expression gets evaluated before others.
order of operations
The rule that multiplication and division happen before addition and subtraction, with ties broken left to right.
expression
A combination of values and operators that collapses down to a single value.
parentheses
Symbols that force everything inside them to be evaluated first, overriding normal precedence.

Watch it explained

  1. How it worksHow does Java collapse a long expression one operator at a time using precedence?
  2. Worked exampleFind the value of 10 - 2·3 + 8 / 4 and show the order the operators fire in.
  3. Worked exampleFind what (10 - 2)·(3 + 8) / 4 evaluates to and where the parentheses change the order.
  4. Common mistakeWhy isn't Java simply evaluating every expression strictly left to right?

Check yourself

Your turn1 of 2
What is the value of 31 - 5·6 + 6?

End of topic.