Java operator precedence
When more than one operator appears in an expression, after who should and who does? This involves the priority of the operators of the problem. In an expression more than one operator, the operator precedence may lead to the conclusion that different results vary widely.
For example, (1 + 3) + (3 + 2) * 2, if the expression is the highest priority number is calculated by adding the answer is 18, if the highest priority in accordance with the multiplication, the answer is 14.
Again, x = 7 + 3 * 2; wherein x obtained 13 instead of 20 because the multiplication operator has higher precedence than the addition operator, so the first 3 * 2 is calculated to give 6, and 7 together.
The table top having the highest priority in the operator table, the bottom of the lowest priority in the table.
category | Operators | Relevance |
---|---|---|
suffix | () []. (Dot operator) | Left to right |
Unitary | + + - !〜 | From right to left |
Multiplicative | * /% | Left to right |
Additive | + - | Left to right |
Displacement | >> >>> << | Left to right |
relationship | >> = << = | Left to right |
equal | == != | Left to right |
Bitwise AND | & | Left to right |
Bitwise XOR | ^ | Left to right |
Bitwise or | | | Left to right |
Logic and | && | Left to right |
Logical or | | | | Left to right |
condition | ?: | From right to left |
Assignment | = + = - = * = / =%= >> = << =&= ^ = | = | From right to left |
comma | , | Left to right |
Note:
-
We do not need to deliberately remember these priorities, the expression inside the parentheses precedence to organize! !
-
Logical and, logical or, logical non-priority must be familiar with! (Non logic> logic> or logic). Such as:
-
a || b && c calculation result is: a || (b && c), instead of (a || b) && c