Operator Precedence in Java with Example
Operator Precedence in Java with Example
In real life when we solve an expression containing multiple operators we follow some rules. For
example in an expression 2+3*4, we do the multiplication first before addition because the
multiplication operator has higher precedence than addition operator. The same applies in java
as well.
In java, operator precedence is a rule that tells us the precedence of different operators.
Operators with higher precedence are evaluated before operators with lower precedence. For
example in expression a+b*c, the operator * will be evaluated before + operator, because
operator * has higher precedence than + operator.
Table bellow shows the precedence of operators in decreasing order, the operators appearing
first in table have higher precedence than operators appearing later. Operators appearing in
same row of table have equal precedence. When operators of equal precedence appears in the
same expression, a rule governs the evaluation order which says that all binary operators except
for the assignment operator are evaluated from left to right while assignment operator is
evaluated from right to left. For example in expression 2+3-4, 2 and 3 is added first then 4 is
subtracted from it. Consider a and b as two operands for the examples given in below table.
Logical OR || a||b
Ternary ?: a = a>2 ? a : b
The postfix operator(eg. a++, a--) has the highest precedence in java.
Assignment operator and it's different forms has the lowest precedence in java.
The operands of operators are evaluated from left to right. For example in expression +
+a + b--, the operand ++a is evaluated first then b-- is evaluated.
Every operand of an operator (except the conditional operators &&, ||, and ? :) are
evaluated completely before any part of the operation itself is performed. For example
in expression ++a + b--, the addition operation will take place only after ++a and b-- is
evaluated.
The left-hand operand of a binary operator are evaluated completely before any part of
the right-hand operand is evaluated.
All binary operators are evaluated from left to right except assignment operator.
What changes the precedence of the operators in Java ?
Parentheses "()" are used to alter the order of evaluation. For example in an
expression a+b*c, if you want the addition operation to take place first, then rewrite the
expression as (a+b)*c.
class OperatorPrecedence {
int result = 0;
result = 5 + 2 * 3 - 1;
result = 5 + 4 / 2 + 6;
result = 3 + 6 / 2 * 3 - 1 + 2;
result = 6 / 2 * 3 * 2 / 3;
int x = 2;