1Z0-809 · Question #218
Given: class MyClass implements AutoCloseable { int test; public void close() { } public MyClass copyObject() { return this; } } and the code fragment: MyClass obj = null; try (MyClass obj1 = new…
The correct answer is B. 100. Option B is correct because copyObject() returns this - meaning obj and obj1 point to the same heap object. When the try-with-resources block exits, it calls close() on obj1, but that method has an empty body, so nothing actually happens to the object's state. The object with…
Question
Options
- AAn exception is thrown at line n2.
- B100
- CA compilation error occurs because the try block is declared without a catch or finally block.
- DA compilation error occurs at line n1.
How the community answered
(20 responses)- A10% (2)
- B80% (16)
- C5% (1)
- D5% (1)
Explanation
Option B is correct because copyObject() returns this - meaning obj and obj1 point to the same heap object. When the try-with-resources block exits, it calls close() on obj1, but that method has an empty body, so nothing actually happens to the object's state. The object with test = 100 remains in memory, and obj still holds a valid reference to it, so printing obj.test outputs 100.
A is wrong because no exception is thrown - close() is a no-op, and obj is a valid, non-null reference after the block exits. C is wrong because try-with-resources (since Java 7) does not require a catch or finally clause - the resource closing is automatic. D is wrong because obj is declared as MyClass outside the try block and copyObject() returns MyClass, making the assignment at line n1 perfectly valid.
Memory tip: Try-with-resources auto-calls close(), but it does not nullify references or garbage-collect the object. Think of it as a hotel checkout - the room is "closed" to new guests, but your belongings (fields) don't vanish unless the cleanup method explicitly removes them.
Community Discussion
No community discussion yet for this question.