04.09. Precedence of Java Operators

Precedence of Java Operators

  • Eclipse: Oxygen
  • Java: 1.8

In Java, operators have different levels of precedence, which determines the order in which operations are performed. The operator with higher precedence is evaluated first, followed by operators with lower precedence. If two operators have the same precedence, their evaluation order is determined by their associativity.

The following is a list of operators, ordered by precedence from highest to lowest:

  1. Postfix operators (expression++, expression–)
  2. Unary operators (!, ~, ++expression, –expression, +, -)
  3. Multiplicative operators (*, /, %)
  4. Additive operators (+, -)
  5. Shift operators (<<, >>, >>>)
  6. Relational operators (<, <=, >, >=, instanceof)
  7. Equality operators (==, !=)
  8. Bitwise AND operator (&)
  9. Bitwise exclusive OR operator (^)
  10. Bitwise inclusive OR operator (|)
  11. Logical AND operator (&&)
  12. Logical OR operator (||)
  13. Ternary operator (condition ? expression1 : expression2)
  14. Assignment operators (=, +=, -=, *=, /=, %=, <<=, >>=, >>>=, &=, ^=, |=)

The order of evaluation of operators can affect the outcome of an expression. For example, consider the expression 5 + 6 * 3. The multiplication operator has higher precedence than the addition operator, so the expression is evaluated as 5 + (6 * 3), which results in 23. However, if the expression is written as (5 + 6) * 3, the addition operator is evaluated first, resulting in 33.

Here is an example program that demonstrates the precedence of operators in Java:

In this program, the expression a + b / c is evaluated. The division operator has higher precedence than the addition operator, so b / c is evaluated first, resulting in 2. Then, the addition operator is evaluated, resulting in a final value of 12.

The output of the program is:

Result: 12

It is important to understand the order of evaluation of operators in Java, especially when writing complex expressions or calculations. By knowing the precedence of operators, you can ensure that your code produces the expected results.

Preference Category Operator Associativity
1st Postfix () [] . (dot operator)  Left to right
2nd Unary ++ – – ! ~  Right to Left
3rd Multiplicative * / %  Left to right
4th Additive + – Left to right
5th Shift >> >>> << Left to right
6th Relational > >= < <= instanceof Left to right
7th Equality == != Left to right
8th Bitwise AND & Left to right
9th Bitwise XOR ^ Left to right
10th Bitwise OR | Left to right
11th Logical AND && Left to right
12th Logical OR || Left to right
13th Conditional ?: Right to Left
14th Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to Left

Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

Contributed by: Salim Sheikh

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments