Java OCA OCP Practice Question 1938

Question

Which of the following statements, when run independently, produces a NullPointerException at runtime?

  • I. Paths.get("../data").getParent().getParent()
  • II. Paths.get("/data").getParent().getRoot()
  • III. Paths.get("/data").getRoot().getRoot()
  • IV. Paths.get("../data").getRoot().getParent()
  • A. I and III
  • B. I and IV
  • C. II and III
  • D. IV only


D.

Note

The first statement returns a null value, since the path .. does not have a parent.

It does not throw an exception at runtime, since it is not operated upon.

The second and third statements both return paths representing the root (/) at runtime.

Remember that calling getRoot() on a root path returns the root path.

The fourth statement throws a NullPointerException at runtime since getRoot() on a relative path returns null, with the call to getParent() triggering the exception.

Since the fourth statement is the only one to produce a NullPointerException at runtime, Option D is the correct answer.




PreviousNext

Related