关于输入:Java Console class 类

Java: Console class

本问题已经有最佳答案,请猛点这里访问。

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

阅读Java文档,我找到了关于控制台类的语句

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.

为什么字符数组可以被覆盖而字符串不能被覆盖?或者可以用更简单的方法覆盖字符数组?


JVM可以将String保存在一个叫做String pool的东西中,以便更有效地管理String的内存使用。然而,这一点的一个副作用是,即使在您用新的String覆盖了引用之后,它也可以保存在内存中。但是,可以直接覆盖字符数组,因此在这方面更安全。


来自Sun认证Java程序员的Java 6学习指南:

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.