Why Char[] array is more secure (store sensitive data) than String in Java?

Both String and Char[] array are used to store the textual data but choosing one over the other is more difficult. Maybe we can get the idea from the immutability of String why char[] array is preferred over String for storing sensitive information data like password, SSN, etc.

  • Using the plain string is a much higher chance of accidentally printing the password to logs or some other insecure places where char[] array is less vulnerable.
  • Since String is immutable, there is no method defined that allow us to change or overwrite the content of the string. This feature makes string objects unstable for storing secure information such as passwords, SSN, etc. We should always store the secure information in char[] array rather than String.
  • Since String is immutable if we store the password as plain text it will be available in memory until the garbage collector cleans it. Since string used String Constant Pool (SCP) for re-usability of a string, there will be a pretty chance that it will remain in memory for a long duration. Since anyone who has access to memory dump can easily find the password in plain text that's another reason should use encrypt password than plain text.
  • If we notice in Java Swing applications, there is a method of JPasswordField getPassword() which return char[] and the deprecated method getText() which return the password in plain text. So java itself recommending to use the get password() method.
  • Another reason for storing a password in char[] array, because char[] can be sanitized, for example, after usage one can override a clear password with junk, while String is immutable in Java.


 Live Demo

public class SecureInfoData {
   public static void main(String args[]) {
      String pwd = "string_pass_word";
      System.out.println("String Password is: " + pwd);
      char charPwd[] = "char_pass_word".toCharArray();
      System.out.println("Character Password is: " + charPwd);


String Password is: string_pass_word
Character Password is: [C@6d06d69c