Java OCA OCP Practice Question 1920

Question

Which statement about the following class is correct?

package mypkg; /*  w  w  w .  j a  v a  2s. com*/
import java.io.*; 
import java.nio.file.*; 
public class Main { 
   public static void copy(Path source, Path target) throws Exception { 
      try (BufferedReader r = Files.newBufferedReader(source); 
            Writer w = Files.newBufferedWriter(target)) { 
         String temp = null; 
         while((temp = r.readLine()) != null) { 
            w.write(temp); 
         } 
      } 
   } 
   public static void main(String[] tooMany) throws Throwable { 
      Main.copy(Paths.get("/original.txt"), 
         FileSystems.getDefault().getPath("/","unoriginal.txt")); 
   } 
} 
  • A. The class compiles without issue.
  • B. The class never throws an exception at runtime.
  • C. The implementation correctly copies a regular file.
  • D. All of the above


A.

Note

The code compiles without issue, but that's about it.

The class may throw an exception at runtime, since we have not said whether or not the source file exists nor whether the target file already exists, is a directory, or is write-protected.

Option B is incorrect.

Option C is also incorrect because the implementation is a flawed copy method.

On a regular file, the code will copy the contents but the line breaks would be missing in the target file.

In order to correctly copy the original file, a line break would have to be written after each time temp is written.

Since it is the only correct statement, Option A is the correct answer.




PreviousNext

Related