Operator precedence in arithmetic and unary expressions
Understanding operator precedence with simple arithmetic and unary operators.
Learning Objectives
- Operator precedence on unary and arithmetic operators.
Source Code
|
Run Output
Code Understanding
int a=1,b=2,c=3; //Three integer variables declared and initialised
int d= a++ – ++c/-b * a + c%++b;
The right hand side of the assignment operator is solved first. This also implies that assignment operator has the last precedence amongst operators.
We divide the right hand expression computation into following steps
STEP 1: 1 – ++3/-2 * 2 + 3%++2
All the variable values are put with unary postfix is resolved first in (right to left on individual term) left to right in whole expression. First a will yield 1 as it has postfix so first instance will not change value, second a will become 2 as previous instance postfix will increase it.
STEP 2: 1 – 4/-2 * 2 + 4%3
Unary pre will be resolved now in (right to left on individual term) left to right order for whole expression. First ++c will make it 4 and second c will be 4 as it is already 4 now because of its prefix increment done earlier.
STEP 3: 1 – 4/-2 * 2 + 4%3
unary negation will be applied, visually it will not have any impact
STEP 4: 1 – -4 + 1
Multiplication, division and modulus will be applied in left to right order. For this reason 4/-2 will happen before multiplication as evaluation is left to right.
STEP 5: 1 + 4 + 1
Reduced to the level of addition subtraction
STEP 6: Final Computation which yields 6
System.out.println(d);
Output is printed.
Notes
- The operator precedence table can be seen at this link.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Common Errors
- Student often try to do make these evaluations in one go and errors are quite likely. The stepwise approach is always better.
Suggested Filename(s): OperatorPrecedence.java
sunmitra| Created: 5-Mar-2018 | Updated: 5-Mar-2018|