Priority of operators in Java

In mathematics, we have priority between plus, subtraction, multiplication and division, in parentheses, in Java, there are similar things in priority between operators if they are used in the same expression. This tutorial, let’s learn about the priority of the operators in Java.

Java has defined the rules for determining the priority of operators in Java. The following table is based on its principle, which operators on the top have higher priority and in a group their priority is determined from left to right.

Priority
a++, a–
++a, –a, +a, -a, !
* (multiplication), / (division), % (modular division)
+ (plus), – (subtraction)
<, >, <=, >=
==, !=
&&, ||
=, +=, -=, *=, /=, %=

For example:

In the above expression, the operators *,  /, % will be calculated first. The expression a %  b * c has two operators, % and *, with same priority, so the calculation will be from left to right. a% b will produce 4 multiplying by 30 will produce 120. The expression a / b will produce result 1. And the final result will be 120 + 1 = 121.

There is a way for us to edit the default priority of these operators using parentheses. Expressions in parentheses will be calculated by Java, and after completing those expressions, the next calculation will be based on priority.

Back to the example above and add parentheses as follows:

the final value will be 21.

Add Comment