Java OCA OCP Practice Question 1924

Question

What is the result of executing the following program?

Assume the path /f1 exists and is non-empty, and the directory tree is fully accessible within the file system.

package mypkg; /*w w w . j  ava 2s.  com*/
import java.io.*; 
import java.nio.file.*; 
public class Main { 
   public static boolean m(Path p1) throws IOException { 
      if(!Files.isDirectory(p1) && !Files.isSymbolicLink(p1)) 
         return Files.delete(p1); 
      else return true; 
   } 
   public static void main(String[] argv) throws IOException { 
      File f1 = new File("/f1"); 
      for(File f : f1.listFiles()) { 
         System.out.println(m(f.toPath())); 
      } 
   } 
} 
  • A. The program prints a list of only true values.
  • B. The program prints a mix of true and false values.
  • C. The code does not compile.
  • D. The code compiles but prints an exception at runtime.


C.

Note

The Files.delete() method has a return type of void, not boolean, resulting in a compilation error and making Option C the correct answer.

There is another method, Files.deleteIfExists(), which returns true if the file is able to be deleted.

If it was used here instead, the file would compile and print a list of true values, making Option A the correct answer.

As stated in the description, the directory tree is fully accessible, so none of the Files.deleteIfExists() would return false.




PreviousNext

Related