Oracle Certified Professional Java Se 8 Programmer · Free Practice Question Medium
Question 11
Imagine below path exists:
- F:.
- └───A
- └───B
Given code of Test.java file:
- package com.udayan.ocp;
- import java.io.*;
- public class Test {
- public static void main(String[] args) {
- File dir = new File("F:" + File.separator + "A" + File.separator + "B");
- System.out.println(/*INSERT*/);
- }
- }
Which of the following replaces /*INSERT*/, such that on execution 'F:\' is displayed on to the console?
Select 2 options.
-
A
dir.getParentFile().getParentFile() -
B
dir.getParent().getParent() -
C
dir.getParentFile().getParent() -
D
dir.getParent().getParentFile()
Reveal correct answers
Correct answers: A, C
Explanation
File class has below 2 methods:
public File getParentFile() {...}
public String getParent() {...}
toString() method of File class prints the abstract path of file object on to the console.
dir.getParentFile() => returns a File object for abstract path 'F:\A'.
dir.getParentFile().getParentFile() => returns a File object for abstract path 'F:\', when this file object is passed to println method, its toString() method is invoked and 'F:\' gets printed on to the console.
dir.getParentFile().getParent() => Returns a String object containing "F:\".
dir.getParent() returns String and String class doesn't contain getParentFile() and getParent() methods.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
