Java Operator Precedence Explained: Rules, Associativity, and Examples

0

Java expressions can contain several operators at the same time. When that happens, Java needs a clear set of rules to determine which operation should be performed first. These rules are called operator precedence.

Understanding precedence prevents a surprisingly common class of bugs: the program compiles successfully, but the expression produces a result different from what the developer expected.

Why Operator Precedence Matters

Consider this expression:

int result = 10 + 5 * 2;

System.out.println(result);

A beginner might calculate from left to right and expect 30. Java, however, performs multiplication before addition, so the actual result is 20.

10 + (5 * 2)
10 + 10
20

The important lesson is that Java does not simply evaluate every expression from left to right. Operator precedence determines which operators get priority.

Real-World Analogy

Think of a restaurant kitchen handling several orders. Some tasks have priority because they must happen before others. Similarly, Java follows a hierarchy when evaluating an expression.

Parentheses can override that hierarchy, just as a manager can explicitly tell the kitchen which task must be handled first.

Remember: When you are unsure about how an expression will be evaluated, use parentheses. Clear code is usually better than code that depends on the reader remembering a complicated precedence rule.

Java Operator Precedence

Priority Operators Category
Highest () [] . Parentheses, array access, member access
High ++, --, +, -, ~, ! Unary operators
*, /, % Multiplication, division, remainder
+, - Addition, subtraction
<<, >>, >>> Shift operators
<, <=, >, >=, instanceof Relational operators
==, != Equality operators
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
&& Logical AND
|| Logical OR
?: Ternary operator
Lowest =, +=, -=, *=, /=, %= Assignment operators

Parentheses Have the Highest Practical Priority

Parentheses explicitly tell Java which expression should be evaluated first.

int result = (10 + 5) * 2;

System.out.println(result);

The parentheses force the addition to happen first:

(10 + 5) * 2
15 * 2
30

Compare that with:

int result = 10 + 5 * 2;

Here multiplication happens first, producing 20.

Multiplication Before Addition

Multiplication, division, and remainder have higher precedence than addition and subtraction.

int result = 20 + 12 / 3;

System.out.println(result);

Java evaluates the division first:

20 + (12 / 3)
20 + 4
24

This same rule applies to the remainder operator.

int result = 10 + 7 % 3;

System.out.println(result);

The remainder is calculated first, so the result is 11.

Operators with the Same Precedence

When operators have the same precedence, associativity determines the evaluation direction.

For example, multiplication and division have the same precedence. They are evaluated from left to right.

int result = 24 / 4 * 2;

System.out.println(result);

Java evaluates this as:

(24 / 4) * 2
6 * 2
12

It does not evaluate 4 * 2 first merely because multiplication appears in the expression.

Associativity

Associativity describes the direction in which operators of the same precedence are grouped.

Operator Group Typical Associativity
Most arithmetic, relational, logical, and bitwise operators Left to right
Unary operators Right to left
Ternary operator Right to left
Assignment operators Right to left

Associativity becomes particularly important with assignments.

int a;
int b;
int c;

a = b = c = 10;

Assignment associates from right to left, so Java effectively evaluates it as:

a = (b = (c = 10));

All three variables therefore receive the value 10.

Unary Operators Have High Precedence

Unary operators such as ++, --, !, ~, unary plus, and unary minus have high precedence.

int value = 5;

int result = -value * 2;

System.out.println(result);

The unary minus is applied before multiplication:

(-value) * 2
-5 * 2
-10

Relational Operators and Equality Operators

Relational operators such as <, >, <=, and >= have higher precedence than equality operators such as == and !=.

int age = 25;

boolean result = age >= 18 && age <= 60;

System.out.println(result);

Java first evaluates the relational comparisons and then combines their boolean results using logical AND.

Logical AND Before Logical OR

The logical AND operator && has higher precedence than logical OR ||.

boolean result = true || false && false;

System.out.println(result);

Java evaluates the AND operation first:

true || (false && false)
true || false
true

If your intention is different, make it explicit with parentheses.

boolean result = (true || false) && false;

Now the result is false.

Bitwise Operators and Precedence

Bitwise operators also have their own precedence levels. Bitwise AND has higher precedence than XOR, and XOR has higher precedence than bitwise OR.

int result = 4 | 2 & 1;

System.out.println(result);

Java evaluates the bitwise AND first:

4 | (2 & 1)

Since 2 & 1 is zero, the final result is 4.

Practical advice: Bitwise expressions can become difficult to read quickly. Parentheses are strongly recommended when combining multiple bitwise operators, even when you know the precedence rules.

Shift Operators and Arithmetic Operators

Shift operators have lower precedence than addition, subtraction, multiplication, division, and remainder.

int result = 2 + 3 << 1;

System.out.println(result);

Addition happens before the shift:

(2 + 3) << 1
5 << 1
10

This is another situation where parentheses can make the programmer's intention immediately obvious.

Ternary Operator Has Lower Precedence

The ternary operator has lower precedence than most operators discussed so far, which allows expressions such as this:

int score = 75;

String result = score >= 40 ? "Pass" : "Fail";

The comparison is evaluated before the ternary choice.

When a ternary expression is combined with other operators, parentheses can make the intended grouping much easier to understand.

Assignment Operators Have Low Precedence

Assignment operators such as =, +=, and -= have relatively low precedence.

int result;

result = 10 + 5 * 2;

Java evaluates the arithmetic expression first and then assigns the final value to result.

result = (10 + (5 * 2));

A Complex Expression Example

Let's combine several operators:

int a = 10;
int b = 5;
int c = 2;

int result = a + b * c - 4;

System.out.println(result);

Multiplication has the highest priority among these arithmetic operators:

a + (b * c) - 4
10 + (5 * 2) - 4
10 + 10 - 4
20 - 4
16

The final result is 16.

When Parentheses Should Be Used

Knowing precedence does not mean you should avoid parentheses. In professional code, parentheses are often valuable because they communicate intent directly to another developer.

int result = (price + tax) * quantity;

Even if the precedence rules would allow you to write the expression without parentheses, the grouped version immediately communicates the business calculation.

A few extra characters can save another developer from having to mentally reconstruct the precedence rules.

Common Beginner Mistakes

  • Assuming every Java expression is evaluated strictly from left to right.
  • Forgetting that multiplication, division, and remainder have higher precedence than addition and subtraction.
  • Confusing precedence with associativity.
  • Ignoring the difference between && and || precedence.
  • Writing complicated expressions without parentheses.
  • Assuming that operator precedence changes the order in which every part of an expression is evaluated.

Best Practices

  • Know the common precedence rules, especially for arithmetic, comparison, logical, and assignment operators.
  • Use parentheses when they improve clarity or communicate business intent.
  • Avoid unnecessarily clever expressions containing too many different operators.
  • Break complicated calculations into meaningful intermediate variables.
  • Do not rely on readers remembering obscure precedence rules.
  • Treat readability as part of correctness in production code.

Interview Insights

Interviewers often give an expression such as 10 + 5 * 2 and ask for the result. The expected reasoning is that multiplication has higher precedence than addition, producing 20.

Another common question involves the difference between precedence and associativity. Precedence determines which operator has priority. Associativity determines how operators at the same precedence level are grouped.

A strong Java developer should know these rules, but an even stronger developer knows when to stop relying on them and use parentheses or intermediate variables to make the code self-explanatory.

Quick Revision

Rule Example What Happens First
Parentheses override normal precedence (10 + 5) * 2 10 + 5
Multiplication before addition 10 + 5 * 2 5 * 2
Same-level arithmetic operators are left associative 24 / 4 * 2 24 / 4
Relational before logical AND age > 18 && active age > 18
Logical AND before logical OR true || false && false false && false
Arithmetic before assignment result = 10 + 5 10 + 5
Assignment groups right to left a = b = 10 b = 10

Final Takeaway

Operator precedence tells Java which operators should be handled first when an expression contains multiple operations, while associativity determines how operators with the same precedence are grouped. These rules are essential for understanding Java expressions, but professional programming is not about writing expressions that force readers to remember every rule. When an expression becomes even slightly difficult to interpret, use parentheses or split the calculation into meaningful steps. The best code makes the intended order of operations obvious to both the compiler and the human reading it.

Post a Comment

0Comments
Post a Comment (0)