What is the result of compiling and executing the following program?
package mypkg; //from w w w .ja va 2s . c o m import java.io.*; import java.util.*; public class Main { private List<String> list = new ArrayList<>(); private static Main getMain(String name) { return null; } public static void printMain() throws Exception { Console c = new Console(); final String name = c.readLine("What is your name?"); final Main stuff = getMain(name); stuff.list.forEach(s -> c.printf(s)); } public static void main(String[] holidays) throws Exception { printMain(); } }
A.
The constructor for Console is private.
Therefore, attempting to call new Console()
outside the class results in a compilation error, making Option A the correct answer.
The correct way to obtain a Console instance is to call System.console()
.
Even if the correct way of obtaining a Console had been used, and the Console was available at runtime, stuff is null in the printMain()
method.
Referencing stuff.list results in a NullPointerException, which would make Option B the correct answer.