Java OCA OCP Practice Question 2474

Question

What is the output of the following code?

import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;

class Main {//from  w ww .  j a va 2 s .c  o  m
   public static void main(String... args) {
      Path path1 = FileSystems.getDefault().getPath("/main/sub/notes/file.txt");
      Path path2 = Paths.get("code/Hello.java");
      System.out.println(path1.getRoot() + ":" + path2.getRoot());
      System.out.println(path1.getName(0) + ":" + path2.getName(0));
      System.out.println(path1.subpath(1, 3) + ":" + path2.subpath(0, 1));
   }
}
a  \main:null//from  w  w w  .  j a  v a  2 s.c  o m
   file.txt:Hello.java
   sub\notes\file.txt:code\Hello.java

b  \:null
   file.txt:Hello.java
   sub\notes:code

c  main:code
   file.txt:Hello.java
   sub\notes:code

d  \:null
   main:code
   sub\notes:code

e  None of the above
f  Compilation fails


d

Note

The getRoot() method returns the root of a path for an absolute path and null for a relative path.

Because "/main/sub/notes/file.txt" starts with a /, it's considered an absolute path and getRoot() will return / or \ depending on your underlying OS ( \ for Windows and / for UNIX).

Method getName() excludes the root of a path and returns the element of this path, specified by the index parameter to this method.

The element closest to the root in the directory hierarchy has an index of 0 and the element farthest from the root has an index of count-1 (where count is the total number of Path elements).

Method subpath() (small p) returns the subsequence of the name elements of a Path, starting at the method parameter startIndex (inclusive) up to the name element at endIndex(exclusive).




PreviousNext

Related