How does Java resolve operator precedence and associativity, and what is the most common precedence bug you see in real code?
Java uses the standard set of rules that you already know from the C family of languages, and there are three levels worth naming. The multiplicative operators, which are multiplication, division and remainder, bind most tightly of all. The additive operators, which are addition and subtraction, come next. After that come the shift, relational, equality, bitwise and, bitwise or, logical and, logical or, conditional and assignment operators, in that order, and the assignment operator is the loosest of the whole set.
Equality sits below relational, so the expression a == b < c is read as a == (b < c). All of the binary arithmetic operators work from left to right, and the conditional operator works from right to left.
The mistake that actually reaches production is the logical one. The operator && binds more tightly than ||, so the expression a || b && c means a || (b && c). A programmer who means (a || b) && c gets the other grouping, and because both forms compile without complaint, the mistake ships.
public class Main {
public static void main(String[] args) {
int a = 5;
int b = 10;
boolean flag = false;
// The and operator binds more tightly, so this reads as
// (a == 5) or ((b == 10) and flag).
boolean asWritten = a == 5 || b == 10 && flag;
boolean asIntended = (a == 5 || b == 10) && flag;
System.out.println("as written : " + asWritten);
System.out.println("as intended : " + asIntended);
// Addition binds more tightly than a shift.
int value = -16;
System.out.println("-16 >> 2 : " + (value >> 2));
System.out.println("-16 >>> 2 : " + (value >>> 2));
System.out.println("1 + 2 << 3 : " + (1 + 2 << 3));
// When you are not sure, add the brackets. They cost nothing.
boolean explicit = (a == 5 || b == 10) && flag;
System.out.println("explicit : " + explicit);
}
}
Two more facts are worth knowing. The conditional operator is the only operator in Java that takes three parts, and unlike the one in C it needs a result type on both of the branches that can be given to the expression without taking a wrapper apart. Mixing an int and an Integer in the two branches therefore does not compile. And the compound assignment operators, such as +=, are not simply a shorter way of writing x = x + y. The right-hand side is worked out once, changed into the type of the variable, and the operation then happens in that type. That matters for small types, because b += 1 wraps around on a byte while b = b + 1 does not compile without a cast.
The next question in this topic looks at the one operator whose behaviour surprises people most, which is division.