OCP Question 57, Explanation

Given the code fragment:

Path path1 = Paths.get("/app/./sys/");
Path res1 = path1.resolve("log");
Path path2 = Paths.get("/server/exe/");
Path res2 = path2.resolve("/readme/");

Path p1 = Paths.get("/usr/./bin/");
Path r1 = p1.resolve("python");
Path p2 = Paths.get("/var/lib/");
Path r2 = p2.resolve("/home/");

What is the result?

A. /usr/bin/python
B. /usr/python/bin
C. /usr/./bin/python

D. /usr/./bin/python


The correct answer is C.


All we have to remember about the resolve() method in the Path interface is that both overloaded versions follow the same logic, namely:

Okay, so it appears that we again have an ambiguously formulated question here for where’s the guarantee that we are running, say, Linux? Because on some file systems – like the one in Windows – “/home/” isn’t absolute despite the presence of the root component (we have discussed this already in Problem 1). But let’s be realistic and stick to the most natural scenario by assuming that the forward slash and names of the dirs all point to an OS of some *nix flavor.

This means, therefore, that the only valid option is C as “/home/” will be denoting an absolute path. As for Windows, experiments show that the JVM produces the same output as in option C…

If you’re wondering about the dot in “/usr/./bin/python“, resolve() simply can’t be bothered with removing redundant components; to do so, we’ll need to call normalize() on the Path object in question (p1 or r1 in our case).

Leave Comment

Your email address will not be published.