nerdexam
Oracle

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…

Using Java I/O API

Question

Which code line n1, obtains the java.io.Console object?

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)
  • B
    4% (1)
  • C
    68% (17)
  • D
    20% (5)
  • E
    8% (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; Console has no such static method.
  • D and E are wrong because Console has no public constructors - you cannot instantiate it with new, 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 (console is 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

#Console I/O#System.console()#Java I/O API#obtaining streams

Community Discussion

No community discussion yet for this question.

Full 1Z0-829 Practice