How does Java's operator precedence and associativity determine the evaluation order of a complex expression, and what are some common precedence-related mistakes?
Short answer
Operator precedence determines which operators bind more tightly (evaluated first) in an expression with multiple different operators (multiplication/division bind tighter than addition/subtraction, matching standard mathematical convention), and associativity determines the…
Advertisement
AModel answer
Operator precedence determines which operators bind more tightly (evaluated first) in an expression with multiple different operators (multiplication/division bind tighter than addition/subtraction, matching standard mathematical convention), and associativity determines the evaluation order among operators of the SAME precedence level (most binary operators are left-to-right associative, but assignment and unary operators are right-to-left) -- a common mistake involves bitwise operators (&, |) having LOWER precedence than comparison operators (==, <), meaning an expression like `if (a == b & c == d)` actually parses correctly by coincidence in that specific case, but a similar expression relying on unparenthesized mixing of bitwise and comparison operators without careful attention to precedence rules can easily produce surprising, unintended results.
int result = 2 + 3 * 4; // 14, not 20 -- multiplication (*) binds tighter than addition (+)
// A classic precedence pitfall: bitwise AND (&) has LOWER precedence than equality (==)
boolean flag = (a == 1) & (b == 2); // parentheses needed to make intent unambiguous and correct
// boolean confusing = a == 1 & b == 2; // technically works due to precedence rules, but far less readableReal-world example
A code review flags an expression mixing bitwise and comparison operators without explicit parentheses as a readability and correctness risk, even though the code happens to produce the intended result given Java's specific precedence rules, recommending explicit parentheses purely for clarity regardless of technical correctness.
Likely follow-ups
- Why does Java prioritize consistency with mathematical convention for arithmetic operator precedence specifically?
- What's the specific precedence relationship between the ternary conditional operator (?:) and simple assignment (=)?
Related topics