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

Using Parentheses to Override Precedence

Master parentheses to explicitly control evaluation order and make complex expressions readable.

Using Parentheses to Override Precedence

What you'll learn: How to use parentheses to force Java to evaluate parts of an expression in the order you want, not just the default precedence order.

The Core Idea

You've learned that Java follows operator precedence rules (multiplication before addition, etc.). But what if you need a different order? Parentheses give you complete control. Java always evaluates expressions inside parentheses first, regardless of normal precedence.

Think of parentheses like saying "Do this part first!" in bold, red letters. Java stops, calculates what's in the parentheses, and then continues with the rest of the expression.

Why This Matters

Without parentheses, 2 + 3 * 4 equals 14 (multiplication first: 3 * 4 = 12, then 2 + 12 = 14).

But if you want addition first? Use parentheses: (2 + 3) * 4 equals 20. Java evaluates (2 + 3) first, getting 5, then multiplies: 5 * 4 = 20.

Examples in Action

int result1 = 10 - 2 * 3;        // 4 (multiplication first: 10 - 6)
int result2 = (10 - 2) * 3;      // 24 (subtraction first: 8 * 3)

double price = 100 / 5 + 2;      // 22.0 (division first: 20 + 2)
double price2 = 100 / (5 + 2);   // 14.0 (addition first: 100 / 7)

Multiple Levels

You can nest parentheses. Java works from the innermost parentheses outward:

int x = ((2 + 3) * 4) - 1;  // Inner (2+3)=5, then (5*4)=20, then 20-1=19

Readability Bonus

Even when precedence is correct, parentheses make complex expressions clearer for humans:

int area = length * width + 10;   // Correct, but less clear
int area = (length * width) + 10; // Same result, intention clearer

Key Takeaway: Parentheses override all precedence rules, forcing Java to evaluate enclosed expressions first—use them to control evaluation order and improve code clarity.