Empty Lines and readLine Behavior
What you'll learn: How readLine() distinguishes between blank lines in a file and the actual end of the file.
When you're reading files line by line with BufferedReader.readLine(), you'll often encounter blank lines—lines that contain no visible characters. It's crucial to understand that readLine() returns an empty string ("") for blank lines, not null.
The Critical Distinction
Think of readLine() like a mail carrier delivering envelopes. A blank line is like receiving an empty envelope—you still got mail, it just has nothing inside. The end of the file (EOF) is like the mail carrier telling you "that's all the mail for today"—no envelope at all.
- Empty line →
readLine()returns""(an emptyStringobject) - End of file →
readLine()returnsnull(no more data to read)
Why This Matters
Consider a text file like this:
First line
(blank line here)
Third line
When reading it:
String line1 = reader.readLine(); // "First line"
String line2 = reader.readLine(); // "" (empty string, NOT null)
String line3 = reader.readLine(); // "Third line"
String line4 = reader.readLine(); // null (EOF reached)
Notice that line2 is an empty string with length 0. You can call methods on it like line2.isEmpty() without getting a NullPointerException. But line4 is null, signaling there's nothing left to read.
Practical Implications
When looping through a file, always check for null to detect EOF, not for empty strings:
String line;
while ((line = reader.readLine()) != null) {
// This processes empty lines too!
}
If you checked line.isEmpty(), you'd stop prematurely at the first blank line instead of at the actual end of the file.
Key Takeaway: readLine() returns an empty string ("") for blank lines but null only at EOF—never confuse the two when controlling your reading loops.