Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^448) | Exceptions and Additional Control Structures


Guidelines for Choosing a Looping Statement


Here are some guidelines to help you decide when to use each of the three looping statements
(while,do, and for):
1.If the loop is a simple count-controlled loop, the forstatement is a natural
choice. Concentrating the three loop control actions—initialize, test, and
increment/decrement—into one location (the heading of the forstatement)
reduces the chances that you will forget to include one of them.
2.If the loop is an event-controlled loop whose body should execute at least once,
a dostatement is appropriate.
3.If the loop is an event-controlled loop and nothing is known about the first exe-
cution, use a whilestatement.
4.When in doubt, use a whilestatement.

9.3 Additional Java Operators


Java offers a rich, sometimes bewildering, array of operators that allow you to manipulate val-
ues of the primitive data types. Operators you have learned about so far include the assign-
ment operator (=), the arithmetic operators (+,-,*,/,%), the increment and decrement operators
(++,--), the relational operators (==,!=,<,<=,>,>=), the string concatenation operator (+), and
the conditional (short-circuit evaluation) logical operators (!,&&,||). In certain cases, a pair
of parentheses is also considered to be an operator—namely, the type cast operator,

y = (float)someInt;

Java also has many specialized operators that are seldom found in other programming
languages. Table 9.1 lists these additional operators. As you inspect the table, don’t panic—
a quick scan will do.
The operators in Table 9.1, along with those you already know, comprise all of the Java
operators.

Assignment Operators and Assignment Expressions


Java has several assignment operators. The equals sign (=) is the basic assignment operator.
When combined with its two operands, it forms anassignment expression(notan assignment
statement). Every assignment expression has avalueand aside effect—namely, that
the value is stored into the variable denoted by the left side of the expression. For
example, the expression

delta = 2 * 12

has the value 24 and the side effect of storing this value into delta.

Assignment expression A
Java expression with (1) a value
and (2) the side effect of storing
the expression value into a
memory location
Free download pdf