Operator Precedence: Multiplication Before Addition
In this lesson, you'll learn how Java decides which arithmetic operations to perform first when you write complex expressions.
The Problem: Order Matters
When you write an expression like 5 + 3 * 2, should Java add first or multiply first? The answer changes the result dramatically:
- Add first: (5 + 3) * 2 = 16
- Multiply first: 5 + (3 * 2) = 11
Java doesn't guess—it follows operator precedence rules, just like the order of operations you learned in math class.
The Rule: Multiplication, Division, and Modulus Come First
Java always evaluates *, /, and % before + and - when they appear in the same expression without parentheses.
int result = 10 + 5 * 2; // Java calculates 5 * 2 first, then adds 10
System.out.println(result); // Prints: 20 (not 30)
int answer = 20 - 8 / 4; // Division happens first: 8 / 4 = 2, then 20 - 2
System.out.println(answer); // Prints: 18
int value = 3 + 10 % 3 - 1; // Modulus first: 10 % 3 = 1, then 3 + 1 - 1
System.out.println(value); // Prints: 3
Why This Matters
Without understanding precedence, you'll get unexpected results. If you need to change the order, use parentheses to force operations:
int forced = (10 + 5) * 2; // Parentheses override precedence
System.out.println(forced); // Prints: 30
Key Takeaway: Java evaluates *, /, and % before + and - in expressions. Use parentheses to override this default order when needed.