EMZETT.
Login

Operator Precedence

In short: The fixed order in which Java evaluates operators in a nested expression — multiplication-before-addition is only one special case of this.

In more detail: Multiplication/division (* / %) bind more strongly than addition/subtraction (+ -), comparison operators bind more weakly than arithmetic ones, logical AND (&&) binds more strongly than logical OR (||). When in doubt — or to gain readability — explicit parentheses are always worthwhile instead of relying on the rules.

In Depth

int result = 2 + 3 * 4;        // 14, not 20 - * binds more strongly than +
int result2 = (2 + 3) * 4;     // 20 - explicit parentheses force a different order
 
boolean check = 5 > 3 && 2 < 1 || true; // && binds more strongly than ||
// equals: (5 > 3 && 2 < 1) || true  ->  (true && false) || true  ->  false || true  -> true
 
int x = 5;
int y = x++ + ++x; // the order of post-/pre-increment within one expression is tricky
// x++ returns 5 (then x=6), ++x returns 7 (x was already 6) -> y = 5 + 7 = 12, x is now 7

Rough ranking from high to low (excerpt): ++/-- (increment/decrement) → * / % → + - → comparison operators (< > <= >=) → equality operators (== !=) → && → || → assignment (= += -=, binds the weakest). The last example above (x++ + ++x) shows why such combined increment expressions are considered poor style in real code, even though their result is technically well-defined: readability suffers enormously, and a typo between prefix and postfix form completely changes the result. The pragmatic rule in practice: whenever there’s any uncertainty about evaluation order, add explicit parentheses instead of relying on the precedence table — this costs nothing in performance and makes the code immediately unambiguous for every reader.

Associativity as a second rule alongside precedence

Besides pure ranking (which operator “goes first”), associativity determines in which direction operators of equal rank are evaluated — most arithmetic operators are left-associative (10 - 3 - 2 is read as (10 - 3) - 2 = 5, not as 10 - (3 - 2) = 9), while the assignment operator is right-associative (a = b = c is read as a = (b = c) — which is why multiple assignment works right to left). This direction is just as decisive for operators of equal rank as the pure precedence order between different operators.

Why these rules vary slightly in EVERY language

The basic multiplication-before-addition logic is similar across most programming languages (following mathematical conventions), but details like the exact ranking of bitwise operators or the behaviour of special operators do differ between Java, C++, Python, and JavaScript. Anyone switching between several languages should therefore not blindly rely on “how it was in language X”, but should look up the exact Java precedence table when in doubt, or — as recommended above — simply add parentheses.

See also: Operators, Arithmetic Operators, Assignment Operators