Java Reference
In-Depth Information
TABLE 3 . 1 :
Increment/decrement Java
shortcuts.
( Expression ) ( Meaning )
i ++or++ i increment i by 1
i
−−
or
−−
i decrement i by 1
i +=5
increment i by 5
i
decrement i by 5
= 5
Incrementing or decrementing a variable by one (or more) is a very common operation.
This is why Java has several shortcuts for these operations; see Table 3.1.
Note that there is a difference between i ++and++ i . Consider the following code.
int i=3;
int a = i ++;
In this case, the operation increment by one will be performed after the value is assigned.
In other words, ++ after the variable means: use the current value of the variable in the
calculations and perform the increment by one later. In the above example, at the end i
will be equal to 4 and a will be equal to 3. The variable i will be equal to 4 because the
statement i++ incremented i by one. The variable a will be equal to 3 because the old value
of the variable i was assigned to the variable a . Alternatively, consider the following code.
int i=3;
int a=++i;
Now, “++” means increment by one and use the new value. At the end of the code,
the variable i will again be 4, but this time a will be also equal to 4. The reason is that
the new value of the variable i is assigned to the variable a . In general, if the “++” is
after the variable, then this means perform the increment by one later. Conversely, if the
++ is before the variable, then this means perform the increment by one first and use the
new value of the variable in the expression. The operation “
”worksinthesameway,
but it decrements the value of the variable by one. Next, let us examine a more interesting
example.
−−
int i=5;
int a=i+++++i;
The question is what will the value of the variable a be after the code is executed? The
expression i++ + ++i will be executed from left to right. First, i++ will be executed. This
will make the value of i equal to 6. However, since the “++” is after the variable, the old
value 5 will be used for the calculation. Next, the expression ++i will be evaluated. Now
the value of i will become 7. Since the “++” is before the variable, the new value 7 will be
used in the computation. Therefore, Java will add 5 and 7 and assign 12 to the variable a .
Such code is considered “tricky” and should not be part of your program. In general, avoid
using more than one of the arithmetic shortcuts close to each other when the meaning is not
obvious. However, one should be able to understand how tricky code works. For example,
you may have to edit tricky code that is written by someone else.
The last two lines of Table 3.1 show examples of incrementing/decrementing by more
than 1. For example, i+=a is equivalent to writing i=i+a . Similarly, one can write
a*=3 to multiply the value of a by 3 or a/=3 to divide it by 3. It is typical to use the
“++” shortcut in the third part of a for loop. For example, consider the following code.
int numTries ;
 
Search WWH ::




Custom Search