Java OCA OCP Practice Question 2460

Question

Which options are true for the following code?

import java.io.*;
public class Main {
    public static void main(String args[]) throws IOException {
        Console console = System.console();
        String name = "";
        while (name.trim().equals("")) {
            name = console.readLine("What is your name?\n");
            console.printf(name);//from  w  w w  . ja  va2 s . c  o m
        }
    }
}
  • a Class Main can be used to repeatedly prompt a user to enter a name, until the user doesn't enter a value.
  • b console.readLine prints the prompt What is your name? and waits for the user to enter a value.
  • c console.printf(name) prints the value, entered by the user, back to the console.
  • d Class Main can never throw a NullPointerException.


a, b, c

Note

Option (d) is incorrect because System.console() might return null, depending on how the JVM is invoked.

A console isn't available to a JVM if it's started using another program or a background process, or if the underlying OS doesn't support it.

In such cases, console.readLine throws a NullPointerException.




PreviousNext

Related