Java OCA OCP Practice Question 271

Question

Given:

 1: public class Main {
 2:   class MyClass {
 3:      public void close() throws Exception { }
 4:   }// ww  w  .  j  a  va 2  s.  co m
 5:   public static void main(String[] args) throws Exception {
 6:     new Main().run();
 7:   }
 8:
 9:   public void run() throws Exception {
10:       try (MyClass l = new MyClass();) {
11:       }
12:   }
13: }

And the following possible changes:

C1. Replace line 2 with class MyClass implements AutoCloseable {

C2. Replace line 2 with class MyClass implements Closeable {

C3. Replace line 11 with  } finally {}

What change(s) allow the code to compile? (Choose all that apply.)

  • A. Just C1 is sufficient
  • B. Just C2 is sufficient
  • C. Just C3 is sufficient
  • D. Both C1 and C3
  • E. Both C2 and C3
  • F. The code compiles without any changes


A and D are correct.

Note

If the code is left with no changes, it will not compile because try-with-resources requires MyClass to implement AutoCloseable or a sub-interface.

If C2 is implemented, the code will not compile because close() throws Exception instead of IOException.

try-with-resources does not require catch or finally to present.

So the code works equally well with or without C3.




PreviousNext

Related