Java OCA OCP Practice Question 2880

Question

If the current working directory is /user/home, then what is the output of the following code?

Path path = Paths.get("/p1/data/code/java/source.txt"); 
System.out.println(path.subpath(1,3).getName(1).toAbsolutePath()); 
  • A. data/code
  • B. java
  • C. /user/home/code
  • D. /user/home/java/java
  • E. /user/home/source.txt
  • F. /user/home/java/source.txt
  • G. The code does not compile.


C.

Note

First off, the code compiles without issue, so G is incorrect.

Let's take this one step at a time.

First, the subpath() method is applied to the absolute path, which returns the relative path data/code.

Next, the getName() method is applied to the relative path, and since this is indexed from zero, it returns the relative path code.

Finally, the toAbsolutePath() method is applied to the relative path code, resulting in the current directory being incorporated into the path.

The final output is the absolute path /user/home/code, so C is correct.




PreviousNext

Related