Some objects own resources that must be closed. Try-with-resources closes them when the block finishes, including when an exception leaves it. You do not need disk access to learn the lifecycle: StringReader provides input from a string, wrapped in BufferedReader for lines.
Work through the example
BufferedReader.readLine returns the next line without its line terminator, or null at the end. The loop reads a line before its condition, tests for null, processes it, then reads again. This uses the same while-loop pattern as beginner. An empty string is a real blank line; it is not end-of-input.
The declaration inside try's parentheses creates a resource managed by the block. Java closes it automatically. The catch handles IOException, a checked exception from reading or closing. This example converts an unexpected infrastructure failure into IllegalStateException rather than claiming the input was simply invalid. new IllegalStateException("reading failed", error) supplies a message and preserves the original exception as its cause, so failure details are not lost. In the string literal, \n represents a newline character. EOF means end of input, represented here by null. The browser supports these in-memory readers; do not replace StringReader with FileReader here.
Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new StringReader("Read\n\nTest\n"))) {
String line = reader.readLine();
int lines = 0;
while (line != null) {
System.out.println("[" + line + "]");
lines++;
line = reader.readLine();
}
System.out.println(lines);
} catch (IOException error) {
throw new IllegalStateException("reading failed", error);
}
}
}Check your prediction
[Read]
[]
[Test]
3Compare the behavior
AutoCloseable is a built-in interface with a close operation. Try-with-resources requires a resource that implements it; BufferedReader already does. A custom AutoCloseable makes the cleanup order visible. Its close method runs even though work throws. In a real resource class close should release the resource, not merely print. Try-with-resources also preserves a primary exception when closing fails; you do not need to implement that machinery manually.
public class Main {
public static void main(String[] args) {
try (Session session = new Session()) {
System.out.println("Working");
throw new IllegalArgumentException("bad line");
} catch (IllegalArgumentException error) {
System.out.println(error.getMessage());
}
}
}
final class Session implements AutoCloseable {
@Override
public void close() {
System.out.println("Closed");
}
}Check your prediction
Working
Closed
bad lineKeep reading progress separate from filtering
A blank line is a successfully read String of length zero. EOF is null, meaning no further line exists. The loop condition should distinguish those cases; a blank line does not imply later valid records should be ignored. Read the next line on every continuing iteration, including ones whose content you skip.
Resource cleanup is another responsibility. The method that opens the reader in this example owns its lifetime and closes it through try-with-resources. The read loop's parsing decisions do not need to repeat close calls in every branch. A later method accepting a caller-owned reader may instead leave closing to the caller; state that contract explicitly.
Trace three events in order when an exception occurs: work throws, close runs, then the matching catch handles the failure. A demonstration close method prints to make ordering visible; a real close operation releases its resource. The string reader keeps this practice independent of a filesystem.
Debug a plausible mistake
EOF and blank text are different states. The condition currently treats a real blank line as the end of the source. This defect is especially easy to miss with input containing only consecutive valid records.
Repair the blank-line stopping rule
Read all nonblank lines and print Read then Test. A blank line must be skipped without stopping later input. Keep try-with-resources and the IOException policy. Predict what the current program actually prints before changing it and make the smallest repair. Then try "\nRead\n" (a blank line first) and "" (no input at all). The supplied version compiles; its behavior is the problem.
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new StringReader("Read\n\nTest\n"))) {
String line = reader.readLine();
while (line != null && !line.isEmpty()) {
System.out.println(line);
line = reader.readLine();
}
} catch (IOException error) {
throw new IllegalStateException("read failed", error);
}
}
}Hint 1: the idea
The loop's lifetime is controlled by the presence of another line, not its content.
Hint 2: a first step
Keep only the EOF test in the condition and move blank filtering into the body.
Show one solution
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new StringReader("Read\n\nTest\n"))) {
String line = reader.readLine();
while (line != null) {
if (!line.trim().isEmpty()) {
System.out.println(line);
}
line = reader.readLine();
}
} catch (IOException error) {
throw new IllegalStateException("read failed", error);
}
}
}Expected output after repair:
Read
TestThe original printed only Read: !line.isEmpty() in the loop condition made
the blank line end the loop, as if it were EOF. Only null means "no more
input", so the condition keeps just line != null and the blank check moves
inside the body, where it skips one line instead of stopping. With a blank
first line the old loop printed nothing at all.
Practice independently
Readers & Resource Cleanup: practice
So far one block opened the reader and also closed it. Now split those jobs.
Write firstNonblank(BufferedReader reader), which reads until it finds a
nonblank line and returns it trimmed, or returns null at EOF. It reads from a
reader that the caller owns: the caller opens it once and calls
firstNonblank several times. So firstNonblank must not close it, and it lets
IOException go to the caller (throws IOException). For the input
"\nRead\n\n Test \n", three calls print:
Read
Test
nullimport java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
// Open one reader with try-with-resources and call firstNonblank three times.
}
}Hint 1: the idea
Whoever opens a resource closes it. main opens the reader, so main's try-with-resources closes it. If firstNonblank closed it too, the second call would be reading from a closed stream.
Hint 2: a first step
In main: try (BufferedReader reader = new BufferedReader(new StringReader(...)))
with the three printlns inside and catch (IOException error) after. In
firstNonblank, use the same read-before-the-loop pattern as above, but return
the trimmed line as soon as it is nonblank.
Show one solution
import java.io.BufferedReader;
import java.io.StringReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new StringReader("\nRead\n\n Test \n"))) {
System.out.println(firstNonblank(reader));
System.out.println(firstNonblank(reader));
System.out.println(firstNonblank(reader));
} catch (IOException error) {
System.out.println("read failed: " + error.getMessage());
}
}
static String firstNonblank(BufferedReader reader) throws IOException {
String line = reader.readLine();
while (line != null) {
if (!line.trim().isEmpty()) {
return line.trim();
}
line = reader.readLine();
}
return null;
}
}Expected output:
Read
Test
nullfirstNonblank has no try block at all: it neither closes the reader nor catches IOException, because both decisions belong to main, which opened it. Each call continues from where the previous one stopped, which is why the second call finds Test. The third call reaches EOF and returns null.
Change it and test again
Make firstNonblank close the reader it was given: wrap its body in try (BufferedReader own = reader) { ... } and read from own. Predict the output, then run it. You should see Read, then read failed: Stream closed. Which call failed, and which line of the contract did the change break?
Explain before moving on
What does try-with-resources guarantee? What should a parsing rejection do differently from an IOException? Resource management and input validation solve different problems.
Completion is saved in this browser only. It does not measure mastery.