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
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)- A13% (5)
- B5% (2)
- C8% (3)
- D75% (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 -
Pathshas no constructor; it's a utility class with only static methods, sonew Paths(...)won't compile. - B -
toPath()doesn't exist onPaths; that method belongs tojava.io.File(i.e.,new File("/First.txt").toPath()), not thePathsclass. - C -
Pathis an interface, not a class, sonew 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.