Java OCA OCP Practice Question 1874

Question

Which statement best describes the following two methods?

public void m1() throws IOException { 
   final Writer w = new BufferedWriter( 
         new FileWriter("m.open")); 
   w.write("Secret passcode"); 
   w.close(); // w  w  w  .  j a  v  a  2 s .  c  om
} 
public void m2() throws IOException { 
   try(final Writer w = new BufferedWriter( 
         new FileWriter("m.open"))) { 
      w.write("Secret passcode"); 
   } 
} 
  • A. Both methods compile and are equivalent to each other.
  • B. Neither method compiles.
  • C. Only one of the methods compiles.
  • D. The methods compile, but one method may lead to a resource leak.


D.

Note

m1() does not take any steps to ensure the close() method is called after the resource is allocated.

m2() uses a try-with-resources block, which automatically tries to close the resource after it is used.

Option D is the correct answer.

Option A is incorrect since they are not equivalent to each other.

Options B and C are incorrect because both compile without issue.




PreviousNext

Related