0

I got a passwd by Console.readPasswd().When I save it in char array (char[] passwd) and use System.out.println(passwd) .The result is

enter image description here

I input is "123".

import java.io.Console;

public class ConsoleTest1 {

    public static void main(String[] args){
        Console console = System.console();
        String username = console.readLine("user name :");
        System.out.println("user name ="+username);
        char[] password = console.readPassword("passwd:");
        System.out.println("password="+password);
    }
}

But when save the passwd in String passwd(I know it's not recommended)

import java.io.Console;

public class ConsoleTest1 {

    public static void main(String[] args){
        Console console = System.console();
        String username = console.readLine("user name :");
        System.out.println("user name ="+username);
        String password = new String(console.readPassword("passwd:"));
        System.out.println("password="+ password);
    }
}

It can be accurately print:

enter image description here

Why?

Clancy Zeng
  • 159
  • 10
  • the meaning of reading it as a password is to keep it secret. printing it open for all to see, isn't keeping it secret – Stultuske Mar 29 '19 at 09:17
  • 1
    In the first case you are printing the address of the array, you can use `Arrays.toString(password)` if you want to print the array – Joakim Danielson Mar 29 '19 at 09:18

1 Answers1

0

Printing a char array directly using System.out.println will print the object representation of the array, hence the [C@232204a1.
In fact, even that representation tells you that it is a char array, as the prefix is [C, the [ indicating the printed object is an array, with the type being C, a char. For more, see.

You need to convert it to a string like in the second example you posted in order for it to be in a human readable format (ignoring all questions of should it be in a human readable format.

adickinson
  • 553
  • 1
  • 3
  • 14