Java OCA OCP Practice Question 2648

Question

Consider the following program:

import java.util.Scanner;

class Main {/*from w  w  w.  j a  v  a 2 s  . c  om*/
        public static void main(String []args) {
                try (Scanner consoleScanner = new Scanner(System.in)) {
                        consoleScanner.close(); // CLOSE
                        consoleScanner.close();
                }
        }
}

Which one of the following statements is correct?

  • a) This program terminates normally without throwing any exceptions.
  • b) This program throws an IllegalStateException.
  • c) This program throws an IOException.
  • d) This program throws an AlreadyClosedException.
  • e) This program results in a compiler error in the line marked with the comment CLOSE.


a)

Note

The try-with-resources statement internally expands to call the close() method in the finally block.

If the resource is explicitly closed in the try block, then calling close() again does not have any effect.

From the description of the close() method in the AutoCloseable interface: "Closes this stream and releases any system resources associated with it.

If the stream is already closed, then invoking this method has no effect.".




PreviousNext

Related