DEV Community

Cover image for Why is char[] preferred over String for passwords in Java ?
Rakesh KR
Rakesh KR

Posted on


Why is char[] preferred over String for passwords in Java ?

In Java, it is generally considered more secure to use a char[] array to store passwords than to use a String object. This is because String objects are immutable, which means that they cannot be modified once they are created. This means that if a String object containing a password is stored in memory, it cannot be securely erased or overwritten, and it may remain accessible to attackers even after it is no longer needed.

In contrast, a char[] array is mutable, which means that its contents can be modified and erased. This means that a password stored in a char[] array can be securely erased or overwritten as soon as it is no longer needed, reducing the risk of the password being accessed by attackers.

Additionally, String objects are often stored in the string pool, which is a shared area of memory where String objects are stored for efficient reuse. This means that multiple references to the same String object may exist in the string pool, and the password may be accessible through any of these references. A char[] array, on the other hand, is not stored in the string pool, so it is less likely to be accessed by attackers.

Overall, the mutability and non-pooling behavior of char[] make it a more secure choice for storing passwords than String, which is why it is generally preferred in Java.

Top comments (0)

50 CLI Tools You Can't Live Without

The top 50 must-have CLI tools, including some scripts to help you automate the installation and updating of these tools on various systems/distros.