Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Medium
Question 4
Given code of Test.java file:
- package com.udayan.ocp;
- import java.io.*;
- import java.nio.file.Path;
- import java.nio.file.Paths;
- public class Test {
- public static void main(String[] args) throws IOException {
- Path path = Paths.get("F:\\A\\B\\C\\");
- System.out.printf("%d, %s, %s", path.getNameCount(), path.getFileName(), path.getName(2));
- }
- }
F: is accessible for reading/writing but is currently blank.
What will be the result of compiling and executing Test class?
- A Runtime Exception
- B 3, C, C
- C 4, C, B
- D 3, C, B
- E 4, null, B
Reveal correct answer
Correct answer: B
Explanation
Root folder or drive is not considered in count and indexing. In the given path A is at 0th index, B is at 1st index and C is at 2nd index.
path.getName(2) returns 'C'.
path.getNameCount() returns 3 (A,B,C) and path.getFileName() returns the last name of the path, which is 'C'.
Given methods doesn't need actual path to physically exist and hence no exception is thrown at Runtime.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
