Java OCA OCP Practice Question 3033

Question

Given these two class declarations:

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

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

Choose the correct option based on this code segment:

try (Closeable closeableImpl = new CloseableImpl();
        AutoCloseable autoCloseableImpl = new AutoCloseableImpl()) {
} catch (Exception ignore) {
    // do nothing
}
finally {
    // do nothing
}
a)   this code segment does not print any output in console

b)   this code segment prints the following output:

     In AutoCloseableImpl.close()/*  w  ww. ja  va 2s .  com*/

c)   this code segment prints the following output:

     In AutoCloseableImpl.close()
     In CloseableImpl.close()

d)   this code segment 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