Java Reference
In-Depth Information
Caution
There are no spaces in the augmented assignment operators. For example,
+ =
should
be
+=
.
Note
Like the assignment operator (
=
), the operators (
+=
,
-=
,
*=
,
/=
,
%=
) can be used to
form an assignment statement as well as an expression. For example, in the following
code,
x += 2
is a statement in the first line and an expression in the second line.
// Statement
System.out.println(
x +=
2
;
x +=
2
);
// Expression
The increment (++) and decrement (- -) operators are for incrementing and
decrementing a variable by 1.
Key
Point
The
++
and
——
are two shorthand operators for incrementing and decrementing a variable by
1
.
These are handy, because that's often how much the value needs to be changed in many pro-
gramming tasks. For example, the following code increments
i
by
1
and decrements
j
by
1
.
increment operator (++)
decrement operator (
--
)
int
i =
3
, j =
3
;
i++;
// i becomes 4
j——;
// j becomes 2
i++
is pronounced as
i
plus plus and
i——
as
i
minus minus. These operators are known as
postfix increment
(or postincrement) and
postfix decrement
(or postdecrement), because the
operators
++
and
——
are placed after the variable. These operators can also be placed before
the variable. For example,
postincrement
postdecrement
int
i =
3
, j =
3
;
++i;
// i becomes 4
——j;
// j becomes 2
++i
increments
i
by
1
and
——j
decrements
j
by
1
. These operators are known as
prefix
increment
(or preincrement) and
prefix decrement
(or predecrement).
As you see, the effect of
i++
and
++i
or
i——
and
——i
are the same in the preceding exam-
ples. However, their effects are different when they are used in statements that do more than
just increment and decrement. Table 2.5 describes their differences and gives examples.
preincrement
predecrement
T
ABLE
2.5
Increment and Decrement Operators
Operator
Name
Description
Example (assume i = 1)
preincrement
Increment
var
by
1
, and use the
new
var
value in the statement
int j = ++i;
// j is 2, i is 2
++var
postincrement
Increment
var
by
1
, but use the
original
var
value in the statement
var++
int j = i++;
// j is 1, i is 2
——var
predecrement
Decrement
var
by
1
,
and use the
new
var
value in the statement
int j = ——i;
// j is 0, i is 0
postdecrement
Decrement
var
by
1
, and use the
original
var
value in the statement
var——
int j = i——;
// j is 1, i is 0