Java Reference
In-Depth Information
Increment and Decrement Operators
A number of operations using the math operators are so commonly used that they have been given
their own operators. The two you'll be looking at here are the increment and decrement operators,
which are represented by two plus signs (++) and two minus signs ( −− ), respectively. Basically,
all they do is increase or decrease a variable's value by one. You could use the normal + and
operators to do this, for example:
myVariable = myVariable + 1;
myVariable = myVariable - 1;
Note You can assign a variable a new value that is the result of an expression
involving its previous value.
However, using the increment and decrement operators shortens this to:
myVariable ++ ;
myVariable −− ;
The result is the same—the value of myVariable is increased or decreased by one—but the code is
shorter. When you are familiar with the syntax, this becomes very clear and easy to read.
Right now, you may well be thinking that these operators sound as useful as a poke in the eye.
However, in Chapter 3, when you look at how you can run the same code a number of times, you'll
see that these operators are very useful and widely used. In fact, the ++ operator is so widely used
it has a computer language named after it: C++. The joke here is that C++ is one up from C. (Well,
that's programmer humor for you!)
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 prefix it like this:
myVar = ++ myNumber 20;
myNumber is first incremented by one, and then myNumber has 20 subtracted from it. It's a subtle
difference, but in some situations a very important one. Take the following code:
myNumber = 1;
myVar = (myNumber ++ * 10 + 1);
 
Search WWH ::




Custom Search