Java OCA OCP Practice Question 1955

Question

Assuming the file referenced below exists and is significantly large, which statement about the following program is correct?.

public class Main { 
   public void jenniferReads(Path p) { 
      Files.lines(p); //from ww  w  .  j  ava 2 s .  co m
   } 
   public void jonReads(Path p) { 
      Files.readAllLines(p); 
   } 
   public static void main(String[] pages) { 
      Path p = Paths.get("/p1/p2.txt"); 
      final Main r = new Main(); 
      r.jenniferReads(p); 
      r.jonReads(p); 
   } 
} 
  • A. The code does not compile.
  • B. The method jenniferReads() is likely to take longer to run.
  • C. The method jonReads() is likely to take longer to run.
  • D. It is not possible to know which method will take longer to run.


A.

Note

The code does not compile because Files.lines() and Files.readAllLines() throw a checked IOException, which must be handled or declared.

For the exam, remember that other than a handful of test methods, like Files.exists(), most methods in the NIO.

2 Files class that operate on file system records declare an IOException.

Now, if the exceptions were properly handled or declared within the class, then jonReads() would likely take more time to run.

Like all streams, Files.lines() loads the contents of the file in a lazy manner, meaning the time it takes for jenniferReads() to run is constant regardless of the file size.

Note the stream isn't actually traversed since there is no terminal operation.

Alternatively, Files.readAllLines() reads the entire contents of the file before returning a list of String values.

The larger the file, the longer it takes jonReads() to execute.

Since the original question says the file is significantly large, then if the compilation problems were corrected, jonReads() would likely take longer to run, and Option C would be the correct answer.




PreviousNext

Related