|
All Java operators are not made equal. Some have higher importance and hence have a higher precedence over the other operators. When you face Java expression with multiple operators and operands, you need to know the precedence of operators. While evaluating from left to right, the operators with higher precedence are evaluated before the operators of lower precedence. Table 9.2 summarizes the precedence of operators from highest to lowest. The unary operators have the highest precedence while the assignment operator has the lowest.
Table 9.2 Precedence of operators
|
Category |
Operators |
Precedence |
|
Unary |
++ -- + - ! ~ () |
Highest | | | | | | | | | V Lowest |
|
Arithmetic |
* / % |
|
|
+ - |
||
|
Shift |
<< >> >>> |
|
|
Comparative |
< > <= >= instanceof == != |
|
|
Bitwise |
& |
|
|
^ |
||
|
| |
||
|
Short circuit |
&& || |
|
|
Conditional |
?: |
|
|
Assignment |
= op= |
Precedence decides which operators will be applied first and which are applied later. For instance, the unary operator ~ may be applied before arithmetic operator % if both are present in given expression. The operators specified in the same line of table 9.2 have the same precedence. Since the order of evaluation is from left to right, the operators with same precedence are applied as per their order while going from left to right in the given expression.
|
|
You can override precedence by enclosing a Java expression in round parentheses. When Java expression is being evaluated, the variables/expression within round parentheses is evaluated first regardless of precedence. |