(^228) | File Objects and Looping Statements
The test in this whilestatement uses the relational operator !=instead of the equals
method. The reason is that equalscompares the contents of two strings, but the meaning of
nullis that the Stringvariable doesn’t even contain the address of a Stringobject. Thus, a
nullStringhas no contents to compare with anything. Be sure that you understand the dis-
tinction between a nullStringand an empty string (""). If the empty string is assigned to a
Stringvariable, then the variable contains the address of a place in memory where a String
object of length 0 is stored. When nullis assigned to a Stringvariable, it has an invalid ad-
dress value that refers to nowhere in memory. The comparison
line.equals(null)
always returnsfalse, because thenullStringhas no contents that can be compared toline. When
line == null
returns true, the equalsmethod in the preceding example throws a NullPointerException.
Because it is an uncaught exception, the application crashes.
Java provides a convenient way of avoiding the need to separately write the priming
read and the read that gets the next value. When the input operation consists of a simple as-
signment statement, we can instead write the loop as follows:
while((line = dataFile.readLine()) != null) // Get a line
{
. // Process it
.
.
}
At first glance, the expression in this whilestatement looks rather strange. The reason for its
strangeness is that there is an aspect of the assignment operator that we haven’t discussed
yet. In the past, we have written the assignment operator in assignment statements:
x = 2;
The assignment operator can also appear in expressions, where it has both a value and a side
effect. The side effect is the action we normally associate with assignment statements: The
result of the expression to the right of = is assigned to the variable to its left. The value that
= returns is the same as the value that is assigned to the variable. An assignment statement
is really just a special form of assignment expression where the side effect (the assignment)