Order of operations

Given the expression b + m*x, is it evaluated as (1) (b + m) * x or (2) b + (m * x)? if your guess is (2), you're correct. You may have guessed that because, in math, multiplication is performed before addition. It's the same way in Java, and it is also true in Java that anything in parentheses is done first.

Multiplication is done before addition because multiplication has higher precedence than addition. There are 46 (by our count) operators in the Java language, and 16 precedence levels, so the “PEMDAS” rule you may have learned in grade school will not suffice here. Instead, programmers memorize the precedence of a handful of operators but in the main rely on the language's precedence table, which specifies the precedence of each operator by ordering it relative to the precedence of the other operators. Table Java Operator Precedence Levels is such a table.

In Java, the rules for determining the order of operations are:

  1. Expressions in parentheses are done first.
  2. Operators with higher precedence are performed before operators with lower precedence.
  3. In an expression with two or more operators with the same precedence, evaluation is left-to-right (with a few exceptions).

Precedence table

Table Java Operator Precedence Levels is adapted from the Operators table in The Java Tutorials .

Java Operator Precedence Levels
Operators Order of evaluation
expr++, expr‐‐ Left to right
++expr, ‐‐expr, +expr, -expr, ~, ! Right to left
() (cast), new Right to left
*, /, % Left to right
+, - Left to right
<<, >>, >>> Left to right
<, >, <=, >=, instanceof Not associative
==, != Left to right
& Left to right
^ Left to right
| Left to right
&& Left to right
|| Left to right
?: Left to right
=, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=, >>>= Right to left

You can also consider array-element access (x[0]) and object-field access (pt.x) as operators because they are operations that yield a value. Considered as operators, they have the highest precedence.

In the Operators section, we illustrated the cast operator with this expression:

((float) minutesWorked) / 60

In Table Java Operator Precedence Levels you can see that the cast operator is higher than division, so we would actually not have needed to surround (float) minutesWorked with parentheses. This expression—(float) minutesWorked / 60—would have worked just fine, because, by Java's rules of operator precedence, the cast would have been performed first, and that's what we needed.

So why did we do it? Because it makes our intention clearer. We may have consulted Java's precedence table and reassured ourselves that our code was correct, but then we are relying on those programmers who inherit our code to know, or consult, the Java precedence table in order to know what our intent in that code is. Better to make it clear, so that their job is easier.