Module: | Classes, Objects, OOPs & Inheritance
Q48: Consider the following statements regarding the Try-With-Resources statement and the AutoCloseable interface:
1. Introduced in Java 7, the try-with-resources statement automatically closes any managed resources immediately after the try block finishes, completely eliminating the need for a boilerplate finally block.
2. For an object to be legally managed by a try-with-resources block, its parent class must strictly implement the java.lang.AutoCloseable or java.io.Closeable interface.
3. If multiple resources are instantiated within the parentheses of a single try-with-resources block, the JVM automatically closes them in the exact chronological order of their creation.
Which of the above statements is/are correct?
2. For an object to be legally managed by a try-with-resources block, its parent class must strictly implement the java.lang.AutoCloseable or java.io.Closeable interface.
3. If multiple resources are instantiated within the parentheses of a single try-with-resources block, the JVM automatically closes them in the exact chronological order of their creation.
Which of the above statements is/are correct?
✅ Correct Answer: A
🎯 Quick Answer:
The correct combination is 1 and 2. Statement 3 is incorrect because the JVM mandates that multiple resources declared in a try-with-resources statement must be closed in the exact reverse order of their creation.Structural Breakdown: The syntax moves instantiation into parentheses: 'try (FileInputStream fis = new FileInputStream("data.txt")) { }'. The moment execution exits the curly braces, the JVM implicitly calls 'fis.close()'. Historical/Related Context: Before Java 7, closing resources was a nightmare.
Developers had to write a try-catch block, and inside the finally block, write another nested try-catch block just to handle the exception that the close() method itself might throw.
Try-with-resources compresses 15 lines of hazardous boilerplate into 3 clean lines.
Causal Reasoning: Resources are closed in reverse order (Statement 3 context) to prevent dependency collisions.
If Resource B (a BufferedReader) requires Resource A (a FileReader) to function, closing Resource A first would violently crash Resource B when it subsequently attempted to flush and close its own data stream.
Closing the outermost wrapper first ensures architectural safety.