Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

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

In Swing, the password field has a getPassword() (returns char[]) method instead of the usual getText() (returns String) method. Similarly, I have come across a suggestion not to use String to handle passwords.

Why does String pose a threat to security when it comes to passwords? It feels inconvenient to use char[].

2 Answers

Strings are immutable in nature which means it cannot be altered once they have been created. Moreover, strings are stored in the heap memory or String pool and remains in memory for a long duration, which poses a security threat. Whereas char[] are mutable in nature which means its content can be erased or modified once its purpose is served. When it's done being used it is cleaned and no one could ever know about the information you had stored. So, for security reasons char[] preferred over String for passwords in Java
While other suggestions here seem valid, there is one other good reason. With plain String you have much higher chances of accidentally printing the password to logs, monitors or some other insecure place. char[] is less vulnerable.

Consider this:

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

pw = "Password".toCharArray();
System.out.println("Array: " + pw);


String: Password
Array: [C@5829428e

Login / Signup to Answer the Question.