Java OCA OCP Practice Question 1779

Question

What is the output of the following application?

package mypkg;/*from   w w  w.j  a  v  a 2s.co m*/
class Login implements AutoCloseable {
   public void close() {
      System.out.print("1");
   }
}
public class Main {
   public static void main(String... lots) {
      try (Login f = new Login()) {
         System.out.print("2");
         throw new ArithmeticException();
      } catch (Exception e) {
         System.out.print("3");
      } finally {
         System.out.print("4");
      }
   }
}
  • A. 214
  • B. 2134
  • C. 2314
  • D. The code does not compile.


B.

Note

The code compiles, so Option D is incorrect.

The order of evaluation for a try-with- resources statement is that the resources are closed before any associated catch or finally blocks are executed.

2 is printed first, followed by 1.

The ArithmeticException is then caught and 3 is printed.

The last value printed is 4, since the finally block runs at the end.

Option B is the correct answer.




PreviousNext

Related