LearnFrenzy
Sign in Take a free test

File Handling, IO and NIO · Find the Error · Question 7

Error: reassigning a try-with-resources variable Answer, explanation & discussion

  • Find the error
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

Main.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

public class Main {
    public static void main(String[] args) throws IOException {
        try (BufferedReader r = new BufferedReader(new StringReader("a\nb"))) {
            System.out.println(r.readLine());
            r = new BufferedReader(new StringReader("c"));
            System.out.println(r.readLine());
        }
    }
}
  • A readLine cannot be called twice
  • B Resource variables are implicitly final, so r cannot be reassigned inside the try block Correct
  • C StringReader must be closed first
  • D BufferedReader needs a size
Correct Answer: Option B

javac: "auto-closeable resource r may not be assigned".

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links