Java Reference
In-Depth Information
find yourself decreasing the value of a variable by a particular amount, an operation
called
decrementing
. To accomplish this, you write statements like the following:
x = x + 1;
y = y - 1;
z = z + 2;
Likewise, you'll frequently find yourself wanting to double or triple the value of a
variable or to reduce its value by a factor of 2, in which case you might write code
like the following:
x = x * 2;
y = y * 3;
z = z / 2;
Java has a shorthand for these situations. You glue together the operator character
(
+
,
-
,
*
, etc.) with the equals sign to get a special assignment operator (
+=
,
-=
,
*=
, etc.). This variation allows you to rewrite assignment statements like the previous
ones as follows:
x += 1;
y -= 1;
z += 2;
x *= 2;
y *= 3;
z /= 2;
This convention is yet another detail to learn about Java, but it can make the code
easier to read. Think of a statement like
x += 2
as saying, “add
2
to
x
.” That's more
concise than saying
x = x + 2
.
Java has an even more concise way of expressing the particular case in which you
want to increment by 1 or decrement by 1. In this case, you can use the increment
and decrement operators (
++
and
--
). For example, you can say
x++;
y--;
There are actually two different forms of each of these operators, because you can
also put the operator in front of the variable:
++x;
--y;
The two versions of
++
are known as the preincrement (
++x
) and postincrement
(
x++
) operators. The two versions of
--
are similarly known as the predecrement
Search WWH ::
Custom Search