nerdexam
Oracle

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

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 exist. What is the result?

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)
  • A
    18% (7)
  • B
    70% (28)
  • C
    5% (2)
  • D
    8% (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.

Full 1Z0-809 Practice