Java OCA OCP Practice Question 1888

Question

Assuming the path /Earth does not exist within the file system, what is the output of the following program?

package mypkg; 
import java.io.*; 
public class Main { 
   public static void main(String[] dig) { 
      File file = new File("/Earth"); 
      System.out.print(file.getParent() 
            +" - " 
            +file.getParent().getParent()); } } 
  • A. / - /
  • B. / - null
  • C. The code does not compile.
  • D. The code compiles but throws an exception at runtime.


C.

Note

The File getParent() method returns a String, not a File object.

The code does not compile on the last line since there is no getParent() method defined in the String class, and Option C is correct.

If the first method call on the last line was changed to getParentFile(), then the code would compile and run without issue, outputting / - null and making Option B the correct answer.

The File class does not require the location to exist within the file system in order to perform some operations, like getParent(), on the path.




PreviousNext

Related