Saturday, October 24, 2015

How to work with Postfix version of increment/decrement operators in JAVA

When increment or decrement operators works in prefix manner then they follow the Use-then-change rule. Java, first use the value of operand and then change the operand’s value.

When an increment or decrement operator follow its operand (i.e, in its postfix form), Java first uses the value of the operand in evaluating the expression before increment or decrementing the operand’s value. For example, the expression
sum = sum + count++ ;
will take place in the following fashion. (Assuming the initial values of the sum and count are 0 and 10 respectively). The expression then execute in the following sequence:
-=0+10;
10=0+10;
10=0+11;

Check out another expression:
P = P * N--;
Will take place in the following fashion. (Assuming the initial values of P and N are 4 and 8 respectively). The expression then execute in the following sequence:
-=4*8;
32=4*8;
32=4+7;

The postfix or decrement operators follow Use-then-change rule i.e., they first use the value of their operand in evaluating the expression and then change (increment or decrement) the operand’s value.
Prefix version of Operator

No comments:

Post a Comment