Java OCA OCP Practice Question 1934

Question

Assuming the data.txt file exists and is readable, what is the result of executing the following application?

package mypkg; // w w  w  . j  a v  a  2s.c  om
import java.io.*; 
import java.nio.file.*; 
public class Main { 
  public void printMain() { 
     try (OutputStream out = System.out) {  // y1 
        Files.copy(out, Paths.get("data.txt")); 
     } catch (IOException e) { 
        throw new RuntimeException(e); 
     } 
  } 
  public static void main(String[] datawork) { 
     new Main().printMain(); 
  } 
} 
  • A. The code compiles but prints an exception at runtime.
  • B. The class does not compile due to line y1.
  • C. The code does not compile for some other reason.
  • D. The program prints the contents of the data.txt file.


C.

Note

Since System.out is a PrintStream that inherits OutputStream and implements Closeable, line y1 compiles without issue.

On the other hand, the Files.copy() does not compile because there is no overloaded version of Files.copy() that takes an OutputStream as the first parameter.

Option C is the correct answer.

If the order of the arguments in the Files.copy() call was switched, then the code would compile and print the contents of the file at runtime, making Option D the correct answer.




PreviousNext

Related