nerdexam
Oracle

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

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 MyClass()) { obj1.test = 100; obj = obj1.copyObject(); // line n1 } System.out.println(obj.test); // line n2 What is the result?

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)
  • A
    10% (2)
  • B
    80% (16)
  • C
    5% (1)
  • D
    5% (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.

Full 1Z0-809 Practice