Java OCA OCP Practice Question 1944

Question

What is the output of the following application?

package mypkg; //from   w w  w  . j  a  v  a 2  s .  co m

import java.nio.file.*; 

public class Main { 
   public Path rebuild(Path p) { 
      Path v = null; 
      for(int i=0; i<p.getNameCount(); i++) 
         if(v==null) v = p.getName(i); 
         else v = v.resolve(p.getName(i)); 
      return v; 
   } 
   public static void main(String... tools) { 
      final Main al = new Main(); 
      Path original = Paths.get("/p1/p2/p3.txt"); 
      Path repaired = al.rebuild(original); 
      System.out.print(original.equals(repaired)); 
   } 
} 
  • A. false
  • B. true
  • C. The code does not compile.
  • D. The code compiles but prints an exception at runtime.


A.

Note

The program compiles and runs without issue, so Options C and D are incorrect.

The process breaks apart the inputted path value and then attempts to reconstitute it.

There is only one problem.

The method call getName(0) does not include the root element.

This results in the repaired variable having a value of p1/p2/p3.txt, which is not equivalent to the original path.

The program prints false, and Option A is the correct answer.




PreviousNext

Related