Examine the code
while ( (line = br.readLine()) != null ) {
// do something
}
First line
is assigned to whatever br.readLine() returns, then line
is compared to null. The parenthesis enforce that order of operations.
The variable line
will keep taking on the value of the text of the next line as the program loops through all lines in the file, until it reaches the end of the file. At that point line
is assigned the value null, which then terminates the loop.
what I don't understand is how the while loop is internally incrementing its counter
There is no counter for this loop. The loop termination condition is line == null
(another way of saying it keeps looping while line != null
). The loop ends when line
is null.
To me, the while loop above means "if the first line (line[0]) is not null
No, line is not an array. It is a string representing a single line of the file, and that value gets updated as each line is read from the file.
In .NET there is a different method
string[] allLines = File.ReadAllLines(path);
That different approach reads all lines of the file into memory at once. That method is handy for reading in small files, while the method you present is much more memory efficient. It streams the contents of the file, only allocating memory for the current line. That approach is far superior for large files.
Note that the buffered reader plays no role in the loop semantics. It is simply a mechanism to more efficiently read the file from disk (or perhaps unnecessary overhead).