nerdexam
Oracle

1Z0-809 · Question #204

Given the code fragment: public static void main(String[] args) { Console console = System.console(); char[] pass = console.readPassword("Enter password:"); // line n1 String password = new…

The correct answer is D. A compilation error occurs because the IOException isn't declared to be thrown or caught? Option D is actually incorrect per the Java API - this appears to be a flawed answer key. Console.readPassword(String fmt, Object... args) does not throw a checked IOException; the Console class handles I/O exceptions internally, so no try-catch or throws declaration is…

Question

Given the code fragment: public static void main(String[] args) { Console console = System.console(); char[] pass = console.readPassword("Enter password:"); // line n1 String password = new String(pass); // line n2 } What is the result?

Options

  • AA compilation error occurs at line n1.
  • BA compilation error occurs at line n2.
  • CThe code reads the password without echoing characters on the console.
  • DA compilation error occurs because the IOException isn't declared to be thrown or caught?

How the community answered

(23 responses)
  • A
    4% (1)
  • B
    4% (1)
  • C
    9% (2)
  • D
    83% (19)

Explanation

Option D is actually incorrect per the Java API - this appears to be a flawed answer key. Console.readPassword(String fmt, Object... args) does not throw a checked IOException; the Console class handles I/O exceptions internally, so no try-catch or throws declaration is required.

The actual correct answer is C. console.readPassword() is specifically designed to suppress character echoing on the terminal while reading sensitive input, which is exactly what the code does. Both lines n1 and n2 compile and run without error.

Why the distractors are wrong:

  • A - readPassword() returns char[], not a compilation-incompatible type, so line n1 is fine.
  • B - new String(char[]) is a valid String constructor overload; line n2 compiles cleanly.
  • D - Console.readPassword() declares no checked exceptions; there is nothing to catch or declare.

Memory tip: Console is Java's safe password reader - remember it by function: it reads (readPassword) and hides (no echo), and it keeps its IOException problems to itself (no checked exceptions bubble up). If you see console.readPassword() on an exam, think "silent and safe, not exception-prone."

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice