Java Reference
In-Depth Information
Figure 4.12 shows the input and output from two sample excutions of the program.
During the first, the condition at line 38 of method
main
is
true
—more than eight stu-
dents passed the exam, so the program outputs a message to bonus the instructor.
The
compound assignment operators
abbreviate assignment expressions. Statements like
variable
=
variable
operator
expression
;
where
operator
is one of the binary operators
+
,
-
,
*
,
/
or
%
(or others we discuss later in
the text) can be written in the form
variable
operator
=
expression
;
For example, you can abbreviate the statement
c = c +
3
;
with the
addition compound assignment operator
,
+=
,
as
c +=
3
;
The
+=
operator adds the value of the expression on its right to the value of the variable on
its left and stores the result in the variable on the left of the operator. Thus, the assignment
expression
c
+=
3
adds
3
to
c
. Figure 4.13 shows the arithmetic compound assignment op-
erators, sample expressions using the operators and explanations of what the operators do.
Assignment operator
Sample expression
Explanation
Assigns
Assume:
int c = 3, d = 5, e = 4, f = 6, g = 12;
+=
c += 7
c = c + 7
10
to
c
-=
d -= 4
d = d - 4
1
to
d
20
to
e
*=
e *= 5
e = e * 5
/=
f /= 3
f = f / 3
2
to
f
3
to
g
%=
g %= 9
g = g % 9
Fig. 4.13
|
Arithmetic compound assignment operators.
Java provides two unary operators (summarized in Fig. 4.14) for adding 1 to or subtracting
1 from the value of a numeric variable. These are the unary
increment operator
,
++
, and
the unary
decrement operator
,
--
. A program can increment by 1 the value of a variable
called
c
using the increment operator,
++
, rather than the expression
c=c+1
or
c+=1
.
An increment or decrement operator that's prefixed to (placed before) a variable is referred
to as the
prefix increment
or
prefix decrement operator
, respectively. An increment or
decrement operator that's postfixed to (placed after) a variable is referred to as the
postfix
increment
or
postfix decrement operator
, respectively.