Java OCA OCP Practice Question 2263

Question

Consider the following program:

import java.nio.file.*;

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

                while(aFilePath.iterator().hasNext()) {
                         System.out.println("path element: " + aFilePath.
                              iterator().next());
                }/*w w w  . ja  v  a2s .c  o m*/
        }
}

Assume that the file D:\directory\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: directory" forever.
  • D. the program prints the following:
path element: directory
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, and the while loop gets into an infinite loop.

in other words, the following loop terminates after printing the directory 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, even if the file path does not exist in the underlying file system, this exception will not be thrown when the program is executed.

Option D is wrong because the program gets into an infinite loop.




PreviousNext

Related