Java OCA OCP Practice Question 1914

Question

Assuming the current working directory is /home, then what is the output of the following program?

1:  package mypkg; 
2:  import java.nio.file.*; 
3:  public class Main { 
4:     public String doTrick(Path path) { 
5:        return path.subpath(2,3) 
6:           .getName(1) /*from   w w  w  .j a va2s. co m*/
7:           .toAbsolutePath() 
8:           .toString(); 
9:     } 
10:    public static void main(String... cards) { 
11:       final Main m = new Main(); 
12:       System.out.print(m.doTrick( 
13:          Paths.get("/bag/of/test/.././main.txt"))); 
14:    } } 
  • A. /home/test
  • B. /home
  • C. The code does not compile.
  • D. The code compiles but prints an exception at runtime.


D.

Note

The code compiles without issue, making Option C incorrect.

Even though test would be dropped in the normalized path /bag/of/main.txt, there is no normalize() call, so path.subpath(2,3) returns test on line 5.

On line 6, the call to getName() throws an IllegalArgumentException at runtime.

Since getName() is zero-indexed and contains only one element, the call on line 6 throws an IllegalArgumentException, making Option D the correct answer.

If getName(0) had been used instead of getName(1), then the program would run without issue and print /home/test, and Option A would have been the correct answer.




PreviousNext

Related