Java OCA OCP Practice Question 2559

Question

Consider the following program:

import java.io.*;

class CloseableImpl implements Closeable {
       public void close() throws IOException {
               System.out.println("In CloseableImpl.close()");
       }/*  w w w. j a  v  a 2s .  c  o  m*/
}

class AutoCloseableImpl implements AutoCloseable {
       public void close() throws Exception {
               System.out.println("In AutoCloseableImpl.close()");
       }
}

public class Main {
       public static void main(String []args) {
               try (Closeable closeableImpl = new CloseableImpl();
                       AutoCloseable autoCloseableImpl
                               = new AutoCloseableImpl()) {
               } catch (Exception ignore) {
                       // do nothing
               }
               finally {
                       // do nothing
               }
       }
}

Which one of the following options correctly shows the output of this program when the program is executed?.

a)      This program does not print any output in console.

b)      This program prints the following output:
      In AutoCloseableImpl.close()//from   www.  j ava  2  s.com

c)      This program prints the following output:
      In AutoCloseableImpl.close()
      In CloseableImpl.close()

d)      This program prints the following output:
      In CloseableImpl.close()
      In AutoCloseableImpl.close()


c)

Note

The types implementing AutoCloseable can be used with a try-with-resources statement.

The Closeable interface extends AutoCloseable, so classes implementing Closeable can also be used with a try-with-resources statement.

The close() methods are called in the opposite order when compared to the order of resources acquired in the try-with-resources statement.

So, this program calls the close() method of AutoCloseableImpl first, and after that calls the close() method on the CloseableImpl object.




PreviousNext

Related