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

Chaining Comparisons and Operator Precedence

Understand how relational and logical operators interact and which operators bind more tightly.

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):

  1. Parentheses: () — always evaluated first
  2. Relational operators: <, >, <=, >= — comparisons
  3. Equality operators: ==, != — equality checks
  4. Logical AND: && — both conditions must be true
  5. Logical XOR: ^ — exactly one condition must be true
  6. 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.