Lesson Completion
Back to course

Operator Precedence and Associativity: The Order of Operations

Beginner
12 minutesβ˜…4.5JavaPlay to Learn

1. The Hook (The "Byte-Sized" Intro)

In a Nutshell: Operator precedence determines which operators execute first in complex expressions. Associativity decides whether equal-priority operators evaluate left-to-right or right-to-left.

Remember PEMDAS from math? 10 + 5 * 2 = 20, not 30. Java follows similar rulesβ€”multiplication before addition!


2. Conceptual Clarity (The "Simple" Tier)

πŸ’‘ The Analogy: Traffic Priority

Think of operators as vehicles at an intersection:

  • Precedence = Traffic lights (who goes first)
  • Associativity = Flow direction (left-to-right lane)

Emergency vehicles (*, /) go before cars (+, -). Same-priority vehicles follow lane direction!

Visual Map

graph LR Expr["10 + 5 * 2"] --> Step1["1. Multiply first<br/>5 * 2 = 10"] Step1 --> Step2["2. Then add<br/>10 + 10 = 20"] style Step1 fill:#F57C00 style Step2 fill:#2E7D32

3. Technical Mastery (The "Deep Dive")

πŸ“˜ Formal Definition

Precedence: Priority level (higher executes first)
Associativity: Direction of evaluation for same-level operators

Precedence Table (High to Low)

LevelOperatorsAssociativityExample
1() [] .Left-to-rightarr[i].method()
2++ -- ! ~Right-to-left!flag
3* / %Left-to-righta * b / c
4+ -Left-to-righta + b - c
5<< >> >>>Left-to-rightx << 2
6< > <= >=Left-to-righta < b
7== !=Left-to-righta == b
8&Left-to-righta & b
9^Left-to-righta ^ b
10|Left-to-righta | b
11&&Left-to-righta && b
12||Left-to-righta || b
13?:Right-to-lefta ? b : c
14= += -= etc.Right-to-lefta = b = c

Mnemonic: Parentheses > Unary > Multiplicative > Additive > Shift > Relational > Equality > Bitwise > Logical > Ternary > Assignment

The "Why" Paragraph

Without precedence, 2 + 3 * 4 would be ambiguous! Java follows mathematical conventions to match human intuition. Associativity matters for non-commutative operators: 10 - 5 - 2 = 3 (left-to-right), not 7 (right-to-left). Assignment's right-to-left associativity enables a = b = 10.


4. Interactive & Applied Code

Complete Example

java
public class PrecedenceDemo { public static void main(String[] args) { // Multiplication before addition int result1 = 10 + 5 * 2; // 10 + 10 = 20 System.out.println("10 + 5 * 2 = " + result1); // Use parentheses to override int result2 = (10 + 5) * 2; // 15 * 2 = 30 System.out.println("(10 + 5) * 2 = " + result2); // Left-to-right associativity int result3 = 20 - 10 - 5; // (20 - 10) - 5 = 5 System.out.println("20 - 10 - 5 = " + result3); // Right-to-left (assignment) int a, b, c; a = b = c = 10; // c=10, then b=10, then a=10 System.out.println("a = b = c = 10 β†’ a=" + a + ", b=" + b + ", c=" + c); // Complex expression int x = 5; int y = 10; boolean flag = x < 10 && y > 5 || x == 0; // Breakdown: // 1. x < 10 β†’ true // 2. y > 5 β†’ true // 3. true && true β†’ true // 4. x == 0 β†’ false // 5. true || false β†’ true System.out.println("\nflag = " + flag); // true // Increment precedence int i = 5; int j = i++ + ++i; // (i++) + (++i) // i++ β†’ use 5, then i=6 // ++i β†’ i=7, use 7 // 5 + 7 = 12 System.out.println("\ni++ + ++i = " + j); // 12 System.out.println("i = " + i); // 7 // Parentheses for clarity int sum = (a + b) * c / (d - e); // Clear intent } }

⚠️ Common Mistakes

Mistake #1: Assuming left-to-right for all

java
a = b = 10; // ❌ NOT (a = b) = 10 // βœ… Right-to-left: b=10, then a=10

Mistake #2: Mixing bitwise and logical

java
if (x > 0 & y < 10) { // ❌ Bitwise, no short-circuit! // Use: if (x > 0 && y < 10)

Mistake #3: Forgetting parentheses

java
int result = a + b << 2; // ❌ (a+b) << 2? or a + (b<<2)? // βœ… Add parentheses: (a + b) << 2

Mistake #4: Increment/decrement confusion

java
int x = 5; int y = x++ * 2; // ❌ (x++) * 2 or x++ * 2? // Increment has LOWER precedence than * // Result: y = 5 * 2 = 10, then x = 6

5. The Comparison & Decision Layer

Precedence Groups

GroupOperatorsMemory Trick
Highest() [] .Parentheses/Access
Unary++ -- ! ~Single operand
Multiplicative* / %"Times, Divide, Remainder"
Additive+ -"Plus, Minus"
Relational< > <= >=Comparison
Equality== !=Exact match
Logical&& ||AND before OR
Ternary?:Three operands
Lowest= += -=Assignment last

When Parentheses Are Needed

graph TD Start{Expression<br/>complexity?} Start --> Simple["Simple<br/>(x + y * z)"] --> No["No parentheses<br/>needed"] Start --> Mixed["Mixed operators<br/>different types"] --> Yes["Add parentheses<br/>for clarity"] Start --> Unclear["Unclear intent"] --> Yes style Yes fill:#F57C00

6. The "Interview Corner" (The Edge)

πŸ† Interview Question #1: "What's the output: int x = 10 + 5 * 2;?"

Answer: 20. Multiplication (*) has higher precedence than addition (+), so 5 * 2 = 10 first, then 10 + 10 = 20.

πŸ† Interview Question #2: "Explain: a = b = c = 10;"

Answer: Right-to-left associativity. Assignment has right-to-left, so:

  1. c = 10
  2. b = (value of c = 10) β†’ b = 10
  3. a = (value of b = 10) β†’ a = 10

πŸ† Interview Question #3: "Why do we need parentheses in (a + b) * c?"

Answer: Without parentheses, a + b * c would multiply b * c first (precedence), then add a. Parentheses override precedence, forcing a + b to execute first.


πŸ’‘ Pro Tips

Tip #1: When in doubt, use parentheses

java
// ❌ Unclear result = a + b << c & d; // βœ… Clear result = ((a + b) << c) & d;

Tip #2: Logical AND before OR

java
if (a && b || c && d) { // Evaluated as: (a && b) || (c && d) }

Tip #3: Assignment returns value

java
if ((line = reader.readLine()) != null) { // Assigns AND checks in one expression }

πŸ“š Real-World Examples

Math: total = price * quantity + tax;
Flags: result = (flags & MASK) >> 2;
Validation: valid = !isEmpty && length > 0;


πŸŽ“ Key Takeaways

βœ… * / % execute before + -
βœ… Use parentheses for clarity
βœ… Assignment is right-to-left
βœ… Logical && before ||
βœ… When unclear, add parentheses!

Final Tip: Code is read 10x more than written. Use parentheses liberally for clarity!

Topics Covered

Java FundamentalsOperators

Tags

#java#operators#expressions#arithmetic#logical#beginner-friendly

Last Updated

2025-02-01