Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^450) | Exceptions and Additional Control Structures
In Java, an expression consisting of a variable and an increment or decrement
expression also becomes an expression statementwhen it is terminated by a semi-
colon. All three of the following are valid Java statements:
alpha++;
beta--;
--gamma;
Each of these statements either increments or decrements the given variable.
Because an assignment is an expression and not a statement, you can use it anywhere
that an expression is allowed. The following statement stores the value 20 into firstInt, the
value 30 into secondInt, and the value 35 into thirdInt:
thirdInt = (secondInt = (firstInt = 20) + 10) + 5;
Although some Java programmers use this style of coding, we do not recommend it. It is
hard to read and error-prone.
In Chapter 6, we cautioned against the mistake of using the=operator in place of the
==operator:
if (alpha = 12) // Wrong
The condition in the ifstatement is an assignment expression, not a relational expression.
The value of the expression is 12, which is not a booleanvalue, so a compiler error results.
In addition to the =operator, Java has several combined assignment operators (+=,=, and
the others listed in Table 9.1). These operators have the following semantics:
Statement Equivalent Statement
i += 5; i = i + 5;
pivotPoint
= n + 3; pivotPoint = pivotPoint * (n + 3 );
The combined assignment operators are another example of “ice cream and cake.”They
are sometimes convenient for writing a line of code more compactly, but you can do just fine
without them. We do not use them in this book.


Increment and Decrement Operators


The increment and decrement operators (++and--) operate only on variables, not on con-
stants or arbitrary expressions. Suppose a variablesomeIntcontains the value 3.The expression
++someIntdenotes pre-incrementation. The side effect of incrementingsomeIntoccurs first, so
the expression has the value 4. In contrast, the expressionsomeInt++denotes postincrementa-
tion.The value of the expression is 3, andthenthe side effect of incrementingsomeInttakes place.
The following code illustrates the difference between pre- and post-incrementation:

Expression statement A state-
ment formed by appending a
semicolon to an assignment ex-
pression, an increment expres-
sion, or a decrement expression

T


E


A


M


F


L


Y


Team-Fly®

Free download pdf