Search

Friday, December 14, 2018

Increment and Decrements

Introduced in Module 1, the++and the– –are Java’s increment and decrements operators. As you will see, they have some special properties that make them quite interesting. Let’s begin by reviewing precisely what the increment and decrements operators do. The increment operator adds 1 to its operand, and the decrements operator subtracts 1.

Therefore,
x = x + 1;
is the same as
x++;
and
x = x - 1;
is the same as
--x;
Both the increment and decrements operators can either precede (prefix) or follow (post fix) the operand. For example,
x = x + 1;
can be written as
++x; // prefix form
or as
x++; // post fix form
In the foregoing example,there is no difference whether the increment is applied as a prefix or a post fix. However, when an increment or decrements is used as part of a larger expression, there is an important difference. When an increment or decrements operator precedes its operand, Java will perform the corresponding operation prior to obtaining the operand’s value for use by the rest of the expression. If the operator follows its operand, Java will obtain the operand’s value before incrementing or decrementing it. Consider the following:
 x = 10;
 y = ++x;

In this case,y will be set to 11. 
However, if the code is written as
x = 10; 
y = x++;
then y will be set to 10. In both cases,xis still set to 11; the difference is when it happens. There are significant advantages in being able to control when the increment or decrements operation takes place.

0 comments:

Post a Comment