Java OCA OCP Practice Question 3182

Question

Consider the following program:

import java.nio.file.*;

public class Main {
     public static void main(String[] args) {
             Path aFilePath = Paths.get("D:\\dir\\file.txt");        // FILEPATH

             while(aFilePath.iterator().hasNext()) {
                     System.out.println("path element: " + aFilePath.iterator().next());
             }//ww  w.j  a  v a2 s.  co  m
     }
}

Assume that the file D:\dir\file.txt exists in the underlying file system.

Which one of the following options correctly describes the behavior of this program?

  • A) The program gives a compiler error in the line marked with the comment FILEPATH because the checked exception FileNotFoundException is not handled.
  • B) The program gives a compiler error in the line marked with the comment FILEPATH because the checked exception InvalidPathException is not handled.
  • C) The program gets into an infinite loop printing "path element: dir" forever.
  • D) The program prints the following:
path element: dir
path element: file.txt


C)

Note

In the while loop, you use iterator() to get a temporary iterator object.

So, the call to next() on the temporary variable is lost, so the while loop gets into an infinite loop.

In other words, the following loop will terminate after printing the "dir" and "file.txt" parts of the path:.

Iterator<Path> paths = aFilePath.iterator();
while(paths.hasNext()) {
          System.out.println("path element: " + paths.next());
}

Option A) is wrong because the Paths.get method does not throw FileNotFoundException.

Option B) is wrong because InvalidPathException is a RuntimeException. Also, since the file path exists in the underlying file system, this exception will not be thrown when the program is executed.

Option D) is wrong because the program will get into an infinite loop).




PreviousNext

Related