Java OCA OCP Practice Question 1936

Question

The Main application is run with an input argument of /data.

The /data directory contains five subdirectories, each of which contains five files.

How many Path values does the following application print?

import java.nio.file.*; 
public class Main { 
   public void m(Path p) throws Exception { 
      Files.walk(p,1) // www . j av a 2 s.  co m
         .map(p -> p.toRealPath()) 
         .forEach(System.out::println); 
   } 
   public static void main(String... argv) throws Exception { 
      new Main().m(Paths.get(argv[0])); 
   } 
} 
  • A. None
  • B. One
  • C. Six
  • D. Thirty-one


A.

Note

The code does not compile, therefore no Path values are printed, and Option A is the correct answer.

The key here is that toRealPath() interacts with the file system and therefore throws a checked IOException.

Since this checked exception is not handled inside the lambda expression, the class does not compile.

If the lambda expression was fixed to handle the IOException, then the expected number of Path values printed would be six, and Option C would be the correct answer.

A maxDepth value of 1 causes the walk() method to visit two total levels, the original /data and the files it contains.




PreviousNext

Related