Java Console; readPassword, how does an array protect against determining the value of the password?


I was reading about the class in one of the java certification books, possibly I've missed something fundamental from a previous chapter, but can someone explain the below?

It mentions, that the readPassword method returns a character array instead of a String, to prevent a potential hacker from finding this String and then finding the password.

How is a character array safer? If you could obtain the values in the array then could you not create a script to loop through various combinations and eventually find the password anyway?

From the documentation:

The Console object supports secure password entry through its readPassword method. This method helps secure password entry in two ways. First, it suppresses echoing, so the password is not visible on the user's screen. Second, readPassword returns a character array, not a String, so the password can be overwritten, removing it from memory as soon as it is no longer needed.

The idea here is that you can call Arrays.fill (or equivalent) to "blank" the char array as soon as you've validated the password, and from that point the password is no longer stored in memory. Since Strings are immutable, the String will remain in the heap until it is garbage collected - which if it manages to get itself interned will be never, and in any other case could still be "too long". All the while it is there, it's potentially vulnerable to sniffing from a variety of vectors.