Char array preferred over string for passwords

There are 2 main reasons of Char array preference over string for passwords.

Strings are immutable:

As you know, Strings are immutable in Java which means we can not change the string, if you try to change any existing String it will produce a new string. Because of this if a password is stored as (String) plain text then password will be available in memory until Garbage collector clears it. So, there are high chances password string will remain in memory for long duration, which is a security threat.

In case of Char Array, the data can be wiped explicitly data once you have done with it. The char array can be overwritten and the password would not be present anywhere in the system, even before garbage collection.


Password as a char[] is less vulnerable than as plain text. If you accidentally print the password to logs, monitors or some other insecure place then following will be the result of plain text and of char[].

public static void main(String[] args) {
    Object pwd = "Password";
    System.out.println("String: " + pwd);
    pw = "Password".toCharArray();
    System.out.println("Array: " + pwd);


String: Password
Array: [C@5829428e
Please follow and like us:
Content Protection by