Java Operator Precedence

Java Operator Precedence

Operator precedence in Java determines which operator is evaluated first when an expression contains multiple operators.
If operators have the same precedence, evaluation happens based on associativity (left-to-right or right-to-left).


🔹 Highest to Lowest Precedence Table

Precedence Level Operators Type Associativity
1️⃣ Highest (), [], . Parentheses, array access, object access Left → Right
2️⃣ ++, -- Unary (postfix) Left → Right
3️⃣ ++, --, +, -, !, ~ Unary (prefix) Right → Left
4️⃣ *, /, % Multiplicative Left → Right
5️⃣ +, - Additive Left → Right
6️⃣ <<, >>, >>> Shift operators Left → Right
7️⃣ <, <=, >, >=, instanceof Comparison Left → Right
8️⃣ ==, != Equality Left → Right
9️⃣ & Bitwise AND Left → Right
🔟 ^ Bitwise XOR Left → Right
1️⃣1️⃣ Bitwise OR
1️⃣2️⃣ && Logical AND Left → Right
1️⃣3️⃣
1️⃣4️⃣ ?: Ternary (conditional) Right → Left
1️⃣5️⃣ Lowest =, +=, -=, *=, /=, etc. Assignment Right → Left

📌 Example 1: Without Parentheses

public class Main {
public static void main(String[] args) {
int result = 10 + 5 * 2;
System.out.println(result);
}
}

Output:

20

Why? * has higher precedence than +, so calculation is:

5 * 2 = 10
10 + 10 = 20

📌 Example 2: With Parentheses

int result = (10 + 5) * 2;
System.out.println(result);

Output:

30

📌 Example 3: Logical + Comparison

System.out.println(5 + 3 > 6 && 2 < 5);

Breakdown:

  • 5 + 38

  • 8 > 6true

  • 2 < 5true

  • true && truetrue

Output:

true

📌 Example 4: Assignment Right-to-Left

int a, b, c;
a = b = c = 10;
System.out.println(a + " " + b + " " + c);

Output:

10 10 10

📌 Example 5: Ternary vs Arithmetic

int x = 10, y = 20;
int result = (x > y) ? x : y + 5;
System.out.println(result);

Output:

25

Because y + 5 is evaluated, since condition x > y is false.


✔️ Summary

  • Operators with higher precedence execute first.

  • Parentheses () can be used to control the order.

  • Assignment and ternary operators evaluate right-to-left.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *