Question 1
A BufferedReader wraps an in-memory character source. The loop drains it, then readLine() is called once more. What is the output? ```java import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new StringReader("a\nb\n")); int count = 0; while (br.readLine() != null) { count++; } System.out.println(count + " " + br.readLine()); } } ```
A. 2 nullCorrect answer
Correct — 'a\nb\n' has exactly two lines, so the loop counts 2, and the extra readLine() after end of stream returns null, which concatenation renders as the text 'null'.
B. 3 null
Counts an empty third line; the trailing \n terminates the line 'b' rather than starting a new empty line, so there are only two lines.
C. Throws IOException
Assumes reading past end throws; readLine() returns null at end of stream instead of throwing.
D. Throws NullPointerException
Assumes concatenating the null result throws; string concatenation renders a null reference as the text 'null' rather than throwing.
Explanation
BufferedReader.readLine() strips the line terminator and returns null — it does not throw — once the end of the stream is reached, so the classic while ((line = readLine()) != null) idiom is what terminates the loop. The source "a\nb\n" contains exactly two lines: the trailing \n terminates the line "b" rather than starting an empty third line, which is why 'B' (3) is wrong. The extra readLine() after EOF simply returns null again (the reader was never closed), and string concatenation renders a null reference as the text "null" instead of throwing NullPointerException.