Course contentsShow
← Java
Lesson 94 of 2,8703. Operators and ExpressionsFree lesson

Common Precedence Pitfalls and How to Avoid Them

Identify typical mistakes like 5 + 3 * 2 evaluating to 11 not 16, and best practices for clarity.

Common Precedence Pitfalls and How to Avoid Them

You'll learn how to spot and fix typical mistakes programmers make when mixing operators, ensuring your expressions evaluate correctly.

The Classic Mistake

The most common pitfall occurs when you forget that multiplication and division happen before addition and subtraction. Consider this expression:

int result = 5 + 3 * 2;

Many beginners expect this to equal 16 (thinking left-to-right: 5 + 3 = 8, then 8 * 2 = 16). But Java evaluates it as 5 + (3 * 2), giving you 11 instead. The multiplication happens first due to higher precedence.

Why This Happens

Think of precedence like a "power ranking" of operators. Multiplication and division are VIPs—they cut to the front of the line. Addition and subtraction wait their turn. When you write 5 + 3 * 2, Java automatically sees 5 + (3 * 2) even without the parentheses.

Best Practices for Clarity

1. When in doubt, use parentheses:

int correct = 5 + (3 * 2);  // 11 - explicit and clear
int intended = (5 + 3) * 2; // 16 - if this was your goal

2. Break complex expressions into steps:

int product = 3 * 2;
int result = 5 + product;  // Much clearer than 5 + 3 * 2

3. Remember the modulus operator has the same precedence as multiplication:

int tricky = 10 + 7 % 3;    // Evaluates as 10 + (7 % 3) = 10 + 1 = 11
int clear = 10 + (7 % 3);   // Same result, but intention is obvious

Key Takeaway: When mixing operators, always add parentheses to make your intent crystal clear—even when precedence rules would work in your favor. Your future self (and teammates) will thank you for the readability.