Java OCA OCP Practice Question 1902

Question

Which statement best describes the following two methods?

public String m1() throws IOException { 
   final BufferedReader r = new BufferedReader( 
         new FileReader("saved.name")); 
   final String name = r.readLine(); 
   r.flush(); /*from w w w . ja v a 2  s.co  m*/
   return name; 
} 



public String m2() throws IOException { 
   try(final BufferedReader r = new BufferedReader( 
         new FileReader("saved.name"))) { 
      final String name = r.readLine(); 
      r.flush(); 
      return name; 
   }
}
 
  • 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.


B.

Note

The flush() method is defined on classes that inherit Writer and OutputStream, not Reader and InputStream.

The r.flush() in both methods does not compile, making Option B the correct answer and Option C incorrect.

The methods are not equivalent even if they did compile, since m2() ensures the resource is closed properly by using a try-with-resources statement, making Option A incorrect for two reasons.

Option D would be correct if the calls to flush() were removed.




PreviousNext

Related