1Z0-829 · Question #31
Which code line n1, obtains the java.io.Console object?
The correct answer is A. // Line n1 String input = console.readLine("Input a number: "); int number = Integer.parseInt(input); if (number % 2 == 0) { System.out.println(number + " is even."); } else { System.out.println(number + " is odd"); }. There appears to be an error in the provided answer key - the actual correct answer is B, not A. Option A shows code that uses an already-obtained console object, but never shows how it was obtained. Console console = System.console(); is the only valid way to obtain a…
Question
Options
- A// Line n1 String input = console.readLine("Input a number: "); int number = Integer.parseInt(input); if (number % 2 == 0) { System.out.println(number + " is even."); } else { System.out.println(number + " is odd"); }
- BConsole console = System.console();
- CConsole console = Console.getInstance();
- DConsole console = new Console(System.in);
- EConsole console = new Console(new InputStreamReader(System.in));
How the community answered
(25 responses)- B4% (1)
- C68% (17)
- D20% (5)
- E8% (2)
Explanation
There appears to be an error in the provided answer key - the actual correct answer is B, not A. Option A shows code that uses an already-obtained console object, but never shows how it was obtained.
Console console = System.console(); is the only valid way to obtain a java.io.Console instance in Java. The Console class has no public constructor - it is a JVM-managed resource accessed exclusively through the static factory method System.console(), which returns the console associated with the current JVM process (or null if none is available, e.g., in an IDE).
- C is wrong because
Console.getInstance()does not exist;Consolehas no such static method. - D and E are wrong because
Consolehas no public constructors - you cannot instantiate it withnew, regardless of what arguments you pass. - A is wrong as a standalone answer because it skips the acquisition step entirely and would cause a compile error (
consoleis undefined at that point).
Memory tip: Think "System provides the Console" - just like System.in and System.out, you always go through the System class. The pattern is System.console(), and since it can return null, always null-check before calling readLine() on it.
Topics
Community Discussion
No community discussion yet for this question.