Java OCA OCP Practice Question 2462

Question

Assuming that a user enters the values eJava and Guru, when prompted to enter username and password values, what values would be sent to file login-credentials.

txt when using the following code?.

public class Main {
    public static void main(String args[]) throws Exception {
        try (PrintWriter pw = new PrintWriter(
                              new File("login-credentials.txt"));) {
            Console console = System.console();
            String username = console.readLine("Username:");
            String pwd = console.readPassword("Password:");

            pw.println(username);//ww  w . jav  a2  s .c o  m
            pw.println(pwd);
            pw.flush();
        }
    }
}
a  eJava//from   ww  w  . j  a  v a  2 s.c o  m
   Guru

b  eJava
   ****

c  eJava
   <BLANK LINE>

d  eJava
   String@b6546

e  Compilation error
f  Runtime exception


e

Note

The code fails to compile because the return type of method readPassword() is char[] and not String.

If the type of the variable pwd is changed from String to char[], the contents of the file login-credentials.txt will match as shown in option (a).

The overloaded println() method in class PrintWriter accepts a char[] parameter and prints its individual characters to the underlying file, OutputStream, or Writer.




PreviousNext

Related