Precedence rules tell in what order operations are done. For example, the rules tell you that 2+3*4 is 14, not 20.

In an arithmetic expression,

  1. Anything inside parentheses is done first.
  2. Unary minus is done next.
  3. Multiplications and divisions are done before additions and subtractions.
  4. Operations of equal precedence are done left to right (for example, 10 - 5 - 1 is 4, not 6).
  5. Assignments are done last.

In a condition,

  1. Anything inside parentheses is done first.
  2. Arithmetic is done before equality and inequality tests.
  3. Logical operations are done after equality and inequality tests.
    1. "Not" (!) is done before "and" (&&)
    2. "And" (&&) is done before "or" (||).
  4. Assignments are done last.

For example, x + 1 > y && y > 0 means ((x + 1) > y) && (y > 0).


Because there are a lot of operations in Java, most programmers do not know the complete table of precedence. Therefore, you should use parentheses for any expressions not fully covered by the above rules.


Every operator has a precedence, as given by Sun's precedence table.