1

Possible Duplicate:
Why is char[] preferred over string for passwords?

Reading the java documentation, i found this statement about Console class

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.

Why a character array can be overwritten and a String not? Or maybe a character array can be overwritted in a more simple way?

Community
  • 1
  • 1
  • 2
    http://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords – kosa Sep 19 '12 at 20:50
  • That is just for information. That thread has good description about why char array preferred over String. Because it is just FYI, I pasted as comment. – kosa Sep 19 '12 at 21:01

2 Answers2

1

A String could be kept in something called a String pool by the JVM to manage memory usage for Strings more efficiently. A side effect of this however, is that it may be kept in memory even after you overwrite the reference with a new String.
A character array however can be directly overwritten, and is therefore safer in this respect.

Keppil
  • 45,603
  • 8
  • 97
  • 119
-1

From the Sun Certified Java Programmer for Java 6 Study Guide:

the readPassword method doesn't return a string: it returns a character array. Here's the reason for this: Once you've got the password, you can verify it and then absolutely remove it from memory. If a string was returned, it could exist in a pool somewhere in memory and perhaps some nefarious hacker could find it.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332