Java Reference
In-Depth Information
As well as placing the ++ or -- after the variable, you can also place it before, like so:
++myVariable;
--myVariable;
When the ++ and -- are used on their own, as they usually are, it makes no difference where they are
placed, but it is possible to use the ++ and -- operators in an expression along with other operators. For
example:
myVar = myNumber++ - 20;
This code takes 20 away from myNumber and then increments the variable myNumber by one before
assigning the result to the variable myVar. If instead you place the ++ before and prefi x it like this:
myVar = ++myNumber - 20;
First, myNumber is incremented by one, and then myNumber has 20 subtracted from it. It's a subtle differ-
ence but in some situations a very important one. Take the following code:
myNumber = 1;
myVar = (myNumber++ * 10 + 1);
What value will myVar contain? Well, because the ++ is postfi xed (it's after the myNumber variable), it
will be incremented afterwards. So the equation reads: Multiply myNumber by 10 plus 1 and then incre-
ment myNumber by one.
myVar = 1 * 10 + 1 = 11
Then add 1 to myNumber to get 12, but this is done after the value 11 has been assigned to myVar. Now
take a look at the following code:
myNumber = 1;
myVar = (++myNumber * 10 + 1);
This time myNumber is incremented by one fi rst, then times 10 and plus 1.
myVar = 2 * 10 + 1 = 21
As you can imagine, such subtlety can easily be overlooked and lead to bugs in code; therefore, it's usu-
ally best to avoid this syntax.
Before going on, this seems to be a good point to introduce another operator: +=. This operator can be
used as a shortcut for increasing the value held by a variable by a set amount. For example,
myVar += 6;
does exactly the same thing as
myVar = myVar + 6;
Search WWH ::




Custom Search