Java OCA OCP Practice Question 2442

Question

What's the output of the following code?

class Box implements AutoCloseable {
    public void emptyContents() {
        System.out.println("emptyContents");
    }/*from ww w .  j av  a  2  s . com*/
    public void close() {
        System.out.println("close");
    }
}
class Main{
    public static void main(String args[]) {
        try (Box box = new Box()) {
            box.close();
            box.emptyContents();
        }
    }
 }
a  close//  ww  w.java  2s. co m
   emptyContents
   java.lang.RuntimeException

b  close
   java.lang.RuntimeException

c  close
   emptyContents
   close

d  close
   java.lang.NullPointerException


c

Note

An implicit or explicit call to method close() doesn't set a resource to null, and you can call methods on it.

So the try block results in the following:.

  • Explicit call to method close()
  • Explicit call to method emptyContents()
  • Implicit call to method close()

No exceptions are thrown, and the code prints the output as shown in option (c).




PreviousNext

Related