Chaining Comparisons and Operator Precedence
What you'll learn: How relational and logical operators work together in complex expressions, and which operators evaluate first.
Understanding Operator Precedence in Complex Conditions
When you combine multiple comparisons and logical operators in a single expression, Java needs rules to decide which operations happen first. This is called operator precedence.
Think of it like the order of operations in math (PEMDAS): just as multiplication happens before addition, certain Java operators bind more tightly than others.
The Precedence Hierarchy
From highest to lowest precedence (tightest binding first):
- Parentheses:
()— always evaluated first - Relational operators:
<,>,<=,>=— comparisons - Equality operators:
==,!=— equality checks - Logical AND:
&&— both conditions must be true - Logical XOR:
^— exactly one condition must be true - Logical OR:
||— at least one condition must be true
How This Works in Practice
int age = 25;
boolean hasLicense = true;
// Without parentheses - relational operators evaluate first
boolean canRent = age >= 21 && hasLicense == true;
// Evaluates as: (age >= 21) && (hasLicense == true)
// More complex example
boolean eligible = age > 18 && age < 65 || hasLicense;
// Evaluates as: ((age > 18) && (age < 65)) || hasLicense
// AND binds tighter than OR
Use parentheses when you're unsure or want to make your intent crystal clear:
boolean result = (age > 18) && (age < 65);
Key Takeaway: Relational operators (<, >, etc.) evaluate before logical operators (&&, ||), and && binds more tightly than ||. When in doubt, use parentheses to make your logic explicit and readable.