(^112) | Arithmetic Expressions
Increment and Decrement Operators
In addition to the familiar arithmetic operators, Java providesincrementanddecrement operators:
++ Increment
-- Decrement
These unary operators take a single variable name as an operand. For integer and floating-
point operands, the effect is to add 1 to (or subtract 1 from) the operand. If numcurrently con-
tains the value 8, for example, the statement
num++;
causes numto contain 9. You can achieve the same effect by writing the assignment statement
num = num + 1;
Java programmers, however, typically prefer the increment operator.
The ++and --operators can be either prefix operators
++num;
or postfix operators
num++;
Both of these statements behave in exactly the same way; that is, they add 1 to whatever is
in num. The choice between the two is a matter of personal preference, although most Java pro-
grammers favor the latter form.
Java allows you to use ++and --in the middle of a larger expression:
alpha = num++ * 3;
In this case, the postfix form of ++gives a different result from the prefix form. In Chapter
10, we examine the ++and --operators in more detail. In the meantime, you should use
them only to increment or decrement a variable as a separate, stand-alone statement:
Variable ++ ;
++ Variable ;
Increment-Statement
Variable –– ;
–– Variable ;
Decrement-Statement