Saturday, October 24, 2015

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

When increment or decrement operators works in prefix manner then they follow the change-then-use rule. Java performs these type of operations before using the value of the operand.

When an increment operator precedes its operand (i.e. in its prefix), Java performs the increment or decrement operation before using the value of the operand. For example, the expression

sum = sum + (++count);
will take place in the following fashion. (Assuming the initial values of sum and count are 0 and 10 respectively). The expression will execute in the following sequence:
0=0+10;
-=0+11;
11=0+11

So from this sequence the sum will have its value in the third execution.

The 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 will execute in the following sequence:

-=4*8;
-=4*7;
28=4*7;
The prefix increment or decrement operators follow Change-then-use rule i.e. they first change (increment or decrement) the value of their operand, then use the new value in evaluating the expression.

No comments:

Post a Comment