Operator precedence talks about priority of operators i.e. which operator is executed when; while, Associativity talks about order in which operators with same priority will be executed. The order can be left to right or right to left.
All operators have rules of precedence and associativity that are used to determine how expressions are evaluated. These rules are exceptional when expressions are put in parentheses. Java applies the operators in arithmetic expressions in a sequence determined by the following rules of operator precedence.
§ Operators in expressions contained within pairs of parentheses are evaluated first.
§ Parentheses are said to be at the "highest level of precedence."
§ In cases of nested or embedded parentheses, the operators in the innermost pair of parentheses are applied first.
§ Unary operators are applied next. If an expression contains several unary operations, operators are applied from right to left.
§ Multiplication and division are performed next.
§ Modulus operators are applied next. If an expression contains several modulus arithmetic operations, operators are applied from left to right.
§ Addition and subtraction operations are applied last. If an expression contains several addition and subtraction operations, operators are applied from left to right. Addition and subtraction also have the same level of precedence.
§ Last priority is given to assignment operators.
§ Only unary operators and assignment operators are done right to left. For example, x=y=z means x=(y=z).
Operator Precedence Group | Associativity | Operator Precedence |
(), [], postfix ++, postfix -- | left | Highest |
unary +, unary -, prefix ++, prefix --, ~, ! | right | |
(type), new | left | |
*, /, % | left | |
+, - | left | |
<<, >>, >>> | left | |
< ,<= , >, >=, instanceof | ||
==, != | ||
& | left | |
^ | left | |
| | left | |
&& | left | |
|| | left | |
?: | left | |
=, +=, -=, *=, /=, %=, <<=, >>=, >>>=, &=, |=, ^= | right | Lowest |
Consider the expression: 1+2*3
For the above an equivalent expression is 1+(2*3) and the value is 7
On the other hand if the expression is: (1+2)*3
The value will be different i.e. 9, because the expression in parentheses gets executed first.
The operator and precedence of some operators is shown in the table below:
Example:
RES = A * (B / C) + D / E - F
The numbers show the order in which the calculations are done.
0 comments:
Post a Comment