Java OCA OCP Practice Question 2228

Question

Bill wants to create a program that reads all of the lines of all of his books using NIO.2.

Unfortunately, Bill may have made a few mistakes writing his program.

How many lines of the following class contain compilation errors?

1:  package mypkg; 
2:  import java.io.*; 
3:  import java.nio.file.*; 
4:  public class Main { 
5:     public void readFile(Path p) { 
6:        try { //from   ww  w .  j ava  2  s.  co  m
7:           Files.readAllLines(p) 
8:           .parallel() 
9:           .forEach(System.out::println); 
10:       } catch (Exception e) {} 
11:    } 
12:    public void read(Path directory) throws Exception { 
13:       Files.walk(directory) 
14:          .filter(p -> File.isRegularFile(p)) 
15:          .forEach(x -> readFile(x)); 
16:    } 
17:    public static void main(String... books) throws IOException { 
18:       Path p = Path.get("collection"); 
19:       new Main().read(p); 
20:    } 
21: } 
  • A. None. Bill's implementation is correct.
  • B. One
  • C. Two
  • D. Three
  • E. Four
  • F. Five


E.

Note

The code does contain compilation errors, so Option A is incorrect.

The first is on line 8.

The readAllLines() method returns a List<String>, not a Stream.

While parallelStream() is allowed on a Collection, parallel() is not.

Next, line 14 does not compile because of an invalid method call.

The correct NIO.2 method call is Files.isRegularFile(), not File.isRegularFile(), since the legacy File class does not have such a method.

Line 18 contains a similar error.

Path is an interface, not a class, with the correct call being Paths.get().

Lastly, line 19 does not compile because the read() method throws Exception, which is not caught or handled by the main() method.

For these four reasons, Option D is the correct answer.




PreviousNext

Related