Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Why to use char[] array over a string for storing passwords in Java?

  • Difficulty Level : Medium
  • Last Updated : 24 Sep, 2021

1. Strings are immutable:  Strings are immutable in Java and therefore if a password is stored as plain text it will be available in memory until Garbage collector clears it and as Strings are used in String pool for re-usability there are high chances that it will remain in memory for long duration, which is a security threat. Strings are immutable and there is no way that the content of Strings can be changed because any change will produce new String. 
With an array, the data can be wiped explicitly data after its work is complete. The array can be overwritten and the password won’t be present anywhere in the system, even before garbage collection.

2. Security: Any one who has access to memory dump can find the password in clear text and that’s another reason to use encrypted password than plain text.  So Storing password in character array clearly mitigates security risk of stealing password. 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

3. Log file safety: With an array, one can explicitly wipe the data , overwrite the array and the password won’t be present anywhere in the system. 
With plain String, there are much higher chances of accidentally printing the password to logs, monitors or some other insecure place. char[] is less vulnerable.


//Java program to illustrate preferring char[] arrays
//over strings for passwords in Java
public class PasswordPreference
    public static void main(String[] args)
        String strPwd = "password";
        char[] charPwd = new char[] {'p','a','s','s','w','o','r','d'};
        System.out.println("String password: " + strPwd );
        System.out.println("Character password: " + charPwd );


String password: password
Character password: [C@15db9742

4. Java Recommendation: Java has methods like JPasswordField of javax.swing as the method public String getText() which returns String is Deprecated from Java 2 and is replaced by public char[] getPassword() which returns Char Array.

This article is contributed by Kanika Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!