Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Medium
Question 29
Given code of Test.java file:
- package com.udayan.ocp;
- import java.nio.file.Path;
- import java.nio.file.Paths;
- public class Test {
- public static void main(String[] args) {
- Path path1 = Paths.get("F:\\A\\B\\C");
- Path path2 = Paths.get("F:\\A");
- System.out.println(path1.relativize(path2));
- System.out.println(path2.relativize(path1));
- }
- }
What will be the result of compiling and executing Test class?
-
A
B\C
..\.. - B An exception is thrown at runtime
-
C
..\..
B\C - D Compilation error
Reveal correct answer
Correct answer: C
Explanation
For 'path1.relativize(path2)' both path1 and path2 should be of same type. Both should either be relative or absolute.
In this case, path1 refers to 'F:\A\B\C' and path2 refers to 'F:\A'.
To easily tell the resultant path, there is a simple trick. Just remember this for the exam.
path1.relativize(path2) means how to reach path2 from path1. It is by doing 'cd ..\..' so, 1st output is '..\..'
path2.relativize(path1) means how to reach path1 from path2. It is by doing 'cd B\C' so, 2nd output is 'B\C'.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
