Java Operator Precedence In Tabular form

An operator is a symbol that operates on one, two, or three operands and provides a value.

Operator precedence is a rule that specifies a priority or an order in which operators in an expression are resolved. Based on precedence order or priority, grouping of terms in an expression are determined that decides the way in which expression gets evaluated.

Operators having higher precedence are always evaluated first, before the operators having lower precedence.

When two operators are having same precedence, they are evaluated as per rule of associativity.

All the binary operators are evaluated from left to right, except assignment operator as it is evaluated from right to left.

Below is list of operators with their precedence and associativity from high to low:

Operator name
Operators
Associativity
Postfix  ( Highest Precedence)
x++, x—
Left to Right
Unary
++x, —x, +x, -x,  ~, !
Right to Left
Multiplicative
*, /,%
Left to Right
Additive
+, –
Left to Right
Shift
<<, >>, >>>
Left to Right
Relational
<, >, >=, <=, instanceOf
Left to Right
Equality
== , !=
Left to Right
Bitwise AND
&
Left to Right
Bitwise exclusive OR
^
Left to Right
Bitwise OR
|
Left to Right
Logical AND
&&
Left to Right
Logical OR
||
Left to Right
Ternary
?:
Right to Left
Assignment   ( Lowest Precedence)
=,  += ,  -= , *=,  /= , %=,  &= , ^=,  |= , <<=,  >>=,  >>>=
Right to Left
 

 

Let suppose, result = 2+3*5,  the answer is not 25, in such expression, precedence and associativity comes into picture, here , multiplicative operator has higher precedence than additive once, so , first 3*5, will provide 15, and adding 2 would give 17.


What is Operator Precedence?

Java operator precedence can be defined as an order in which operators in an expression get evaluated. For example, 1+2*3, would not give 9, first multiplication would take place as it got higher precedence than addition, 2*3 = 6, and adding 1 will give 7.

What is Associativity?

When two or more operators in an expression having same precedence, then a rule called associativity is followed for deciding the order of evaluating an operator in the expression. It can be right to left or left to right.

For example, 2-1+2, as we can see the expression having operators, – and + have same precedence, here associativity rule will apply, for additive operators, associativity works from left to right, meaning the expression get evaluated from left to right, so, ‘-’ will be evaluated first, 2-1, would give 1 and afterwards addition would happen , 1+2 would give 3.

Which java operator has the highest precedence?
Postfix operator has the highest precedence in Java.

Leave a Reply