nerdexam
Oracle

1Z0-809 · Question #202

Given the code fragment: //line n1 System.out.println(IP); Which code fragment, when inserted at line n1, enables the code to print /First.txt?

The correct answer is D. Path IP = Paths.get ("/", "First.txt"). Paths.get() is a static factory method on the java.nio.file.Paths utility class - the correct way to create a Path object in Java NIO.2. Option D passes two string segments ("/" and "First.txt") which Paths.get() joins into /First.txt, and calling System.out.println(IP) on a…

Question

Given the code fragment: //line n1 System.out.println(IP); Which code fragment, when inserted at line n1, enables the code to print /First.txt?

Options

  • APath IP = new Paths ("/First.txt");
  • BPath IP = Paths.toPath ("/First.txt");
  • CPath IP = new Path ("/First.txt");
  • DPath IP = Paths.get ("/", "First.txt");

How the community answered

(40 responses)
  • A
    13% (5)
  • B
    5% (2)
  • C
    8% (3)
  • D
    75% (30)

Explanation

Paths.get() is a static factory method on the java.nio.file.Paths utility class - the correct way to create a Path object in Java NIO.2. Option D passes two string segments ("/" and "First.txt") which Paths.get() joins into /First.txt, and calling System.out.println(IP) on a Path invokes its toString(), printing exactly /First.txt.

Why the distractors fail:

  • A - Paths has no constructor; it's a utility class with only static methods, so new Paths(...) won't compile.
  • B - toPath() doesn't exist on Paths; that method belongs to java.io.File (i.e., new File("/First.txt").toPath()), not the Paths class.
  • C - Path is an interface, not a class, so new Path(...) is illegal - you can't instantiate an interface directly.

Memory tip: Think of Paths (with an s) as the supplier - it supplies Path objects via Paths.get(). Just like Arrays.asList() or Collections.unmodifiableList(), Java NIO.2 follows the pattern of a plural utility class providing static factory methods for the singular interface.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice