5.2 Looping | 229
takes place and then the value returned by the expression is discarded. For example, in the
comparison
(x = 2 + 2) == 5
the value 4 is assigned to the intvariable xas a side effect, and the subexpression (x = 2 +
2)has the result 4, which is compared to the literal 5 , giving a final result of false. When we
use the result of an assignment expression in a comparison, we must enclose the assignment
expression in parentheses because =has the lowest precedence of all the operators. This
example demonstrates why you must be careful not to confuse the =and ==operators in writ-
ing a comparison!
In the whilestatement
while((line = dataFile.readLine()) != null) // Get a line
{
. // Process it
}
lineis assigned the value returned by readLine, and the !=operator compares that same
value (the result of the assignment expression) to null.
Because the parentheses force the input operation to happen before the comparison, the
effect is the same as using a separate priming read. When the flow of control reaches the end
of the loop, it returns to the test in the whilestatement. There another input operation takes
place before the comparison, with the same effect as using a separate input operation at the
end of the loop body. Thus, the input operation in the assignment expression, within the while
statement’s comparison, takes the place of two separate input operations.
If we can write thewhilestatement in this manner, why would we ever need the longer
form with the two separate input operations? When the test in thewhilestatement depends
on something other than the value returned by the input operation, we need to use the longer
form. For example, if an input line contains three numbers that must be converted tointval-
ues and their sum is then compared to zero to decide whether the loop should exit, we can’t
use a simple assignment expression within thewhile. Whenever the condition in thewhile
depends on performing multiple operations on the input value, it is best to code the input
and the operations as separate priming and updating statements before and within the loop.
Looping Subtasks
We have been looking at ways to use loops to affect the flow of control in code. But looping by
itself does nothing.The loop body must perform a task for the loop to accomplish something.
In this section, we look at two tasks—counting and summing—that often are used in loops.
Counting A common task in a loop is to keep track of the number of times the loop has been
executed. For example, the following code fragment reads and counts integer input values