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


Code Learning #JAVA#3735 siteicon   siteicon   siteicon  

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

TC++ #3735

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;

Test it !

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

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|