JavaOperator Precedence

Java Operator Precedence

When a Java expression includes multiple operators, the program needs to decide which operation to perform first. This is where operator precedence comes in — it defines the order in which different operators are evaluated.

Operators with higher precedence are evaluated before those with lower precedence. If two operators have the same precedence, they are generally evaluated from left to right.

Example: Order of Execution

Java
int result1 = 2 + 3 * 4;     // 2 + 12 = 14
int result2 = (2 + 3) * 4;   // 5 * 4 = 20

System.out.println(result1);
System.out.println(result2);
14
20
Explanation
  • In the first line, * (multiplication) has higher precedence than +, so it executes first. → 3 * 4 = 12, then 2 + 12 = 14.

  • In the second line, parentheses ( ) change the normal order. → (2 + 3) = 5, then 5 * 4 = 20.

Tip
Use parentheses generously to make the order of evaluation explicit and your code easier to read — even when not strictly required.