1Z0-809 · Question #91
Given the code fragment: Path p1 = Paths.get("/Pics/MyPic.jpeg"); System.out.println (p1.getNameCount() + ":" + p1.getName(1) + ":" + p1.getFileName()); Assume that the Pics directory does NOT…
The correct answer is B. 2:MyPic.jpeg: MyPic.jpeg. Path objects in Java are purely syntactic - methods like getNameCount(), getName(), and getFileName() parse the path string only and never touch the filesystem, making the missing directory completely irrelevant. For /Pics/MyPic.jpeg, the root / is excluded from name elements…
Question
Options
- AAn exception is thrown at run time.
- B2:MyPic.jpeg: MyPic.jpeg
- C1:Pics/Pics: MyPic.jpeg
- D2:Pics: MyPic.jpeg
How the community answered
(40 responses)- A18% (7)
- B70% (28)
- C5% (2)
- D8% (3)
Explanation
Path objects in Java are purely syntactic - methods like getNameCount(), getName(), and getFileName() parse the path string only and never touch the filesystem, making the missing directory completely irrelevant. For /Pics/MyPic.jpeg, the root / is excluded from name elements, leaving exactly 2 elements: index 0 = Pics and index 1 = MyPic.jpeg, so getNameCount() returns 2, getName(1) returns MyPic.jpeg, and getFileName() (which always returns the last element) also returns MyPic.jpeg - producing 2:MyPic.jpeg:MyPic.jpeg.
A is wrong because no filesystem access occurs, so no exception is thrown. D is the most common trap: getName(1) is index 1, which is the second element (MyPic.jpeg), not the first (Pics). C contains two errors: the count is 2 (not 1), and getName(1) is not Pics/Pics.
Memory tip: Think of the root slash as the "handle" of a file cabinet - it holds everything but isn't a drawer itself. Start counting drawers (name elements) after the root, zero-indexed from left. getFileName() is always the last drawer.
Community Discussion
No community discussion yet for this question.