Java SE 8 Programmer II Exam Question Answer: Result of Resolving Paths in Java

Resolving Paths in Java

Question

Given the code fragment: Path path1 = Paths.get("/app/./sys/"); Path res1 = path1.resolve("log"); Path path2 = Paths.get("/server/exe/"); Path res1 = path1.resolve("/readme/"); System.out.println(res1); System.out.println(res2); What is the result?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

C.

The given code fragment creates two Path objects, path1 and path2, using the Paths.get() method. Then, the resolve() method is called on both path1 and path2 to create two new Path objects, res1 and res2, respectively. Finally, the toString() method is called on both res1 and res2 to print their string representations to the console.

Let's look at each line of code and see what it does:

java
Path path1 = Paths.get("/app/./sys/");

This creates a Path object path1 representing the directory /app/./sys/. The . in /app/./sys/ is a relative directory reference that means "the current directory", but it has no effect on the resulting Path object.

java
Path res1 = path1.resolve("log");

This resolves the relative Path "log" against path1, resulting in a new Path object res1 representing the directory /app/./sys/log. Again, the . in /app/./sys/ has no effect on the resulting Path object.

java
Path path2 = Paths.get("/server/exe/");

This creates a Path object path2 representing the directory /server/exe/.

java
Path res1 = path1.resolve("/readme/");

This resolves the absolute Path "/readme/" against path1, resulting in a new Path object res1 representing the directory /readme/. The leading / in "/readme/" makes it an absolute path, which means it is resolved starting from the root directory.

java
System.out.println(res1); System.out.println(res2);

This prints the string representations of res1 and res2 to the console. Therefore, the output of the code will be:

javascript
/readme/ /server/exe/readme

Therefore, the correct answer is option D: /app/./sys/log /server/exe/readme.