Operator precedence in arithmetic and unary expressions – Computer Sir Ki Class

Code Learning #JAVA#3735

## 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

 class OperatorPrecedence { public static void main(String[] args) { int a=1,b=2,c=3; int d= a++ - ++c/-b * a + c%++b; System.out.println(d); } } .linedwrap { border: 1px solid #c0c0c0; padding-top: 5px; padding-bottom: 5px; border-radius: 4px; background-color:#F8F8F8; } .linedtextarea { padding: 0px; margin: 0px; background-color:#F8F8F8; } .linedtextarea textarea, .linedwrap .codelines .lineno { font-size: 12pt; font-family: monospace; line-height: normal !important; } .linedtextarea textarea { padding-right:0.3em; padding-top:0.3em; border: 0; } .linedwrap .lines { margin-top: 0px; width: 20px; float: left; overflow: hidden; border-right: 1px solid #c0c0c0; margin-right: 10px; } .linedwrap .codelines { padding-top: 5px; } .linedwrap .codelines .lineno { color:#AAAAAA; padding-right: 2px; padding-top: 0.0em; text-align: right; white-space: nowrap; } .linedwrap .codelines .lineselect { color: red; }

## Run Output

``````6
``````

## 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 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.

## 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|

×