Evaluation of Expressions

Operator Precedence

When evaluating an expression, Java evaluates any subexpressions inside parentheses first. When an expression does not have parentheses, certain operators are applied before others. The order in which these operators are applied follow Java's "order of operations" or "operator precedence". This order is as follows (with the things at the beginning of the list happening first):

1.  var++, var-- (post-increment and post-decrement)
2.  +, - (Unary plus and minus), ++var, --var (pre-increment and pre-decrement)
3.  (type) casting
4.  ! (Not)
5.  *, /, % (Multiplication, division, and remainder)
6.  +, - (Binary addition and subtraction)
7.  <,<=, >, >= (Comparison Tests)
8.  ==, != (Equality Tests)
9.  ^ (Exclusive OR)
10. && (Conditional AND) Short-circuit AND
11. || (Conditional OR) Short-circuit OR
12. =, +=, -=, *=, /=, %= (Assignment)

Operator Associativity

When two operators with the same precedence are evaluated, the associativity of the operators determines the order of evaluation.

All binary operators except the assignment operators are "left-associative".

Example of Left-Associative Evaluation

n = a - b + c - d;   
  is the same as:  
n = ((a - b) + c ) - d);


Example of Right-Associative Evaluation

n = a += b = 5;      
  is the same as:  
n = (a += (b = 5));


If you are not sure what gets evaluated first, or just as a courtesy to readers of your code, ALWAYS use parentheses to make the expression evaluated in the order you desire.

Example

double value1 = (i++) + ((x*4) % n);  //easy to read
double value2 = i++ + x * 4 % n;      //hard to read - don't do this