Why is char[] preferred over String for passwords?
It is generally considered more secure to use a char[]
array to store passwords because it can be wiped from memory more easily than a String
object. When a String
object is created in Java, it is stored in a string pool, which is a memory region where the JVM stores all String
objects. When a char[]
array is used to store a password, it can be overwritten or zeroed out after it is used, so that it is not stored in memory where it could potentially be accessed by an attacker. By contrast, a String
object that has been used to store a password will remain in the string pool until the JVM decides to garbage collect it, which means it could potentially be accessed by an attacker if the system is compromised. Therefore, it is generally considered more secure to use a char[]
array to store passwords because it can be wiped from memory more easily than a String
object.