Why Char Array is More Secure to Store Sensitive Data than String in Java



Both String class and Char[] array in Java are used to store textual data. However, Strings are immutable, which means you can't make changes to a String once defined, and the char[] array is not immutable.

In the official documentation of Java Cryptography Architecture, it is clearly written that String objects are not suitable for storing sensitive data, such as passwords, SSN, etc. Use a char array instead, as it is more secure than String.

This article will help you understand why char[] array is used to store sensitive data.

Char Array is more secure than String

Let's discuss why we should always store secure information in a char[] array rather than a String in Java:

  • Using the plain string is a much higher chance of accidentally printing the password to logs or some other insecure places where a char[] array is less vulnerable.
  • If we want to change a password in the future, there is no predefined method that allows us to change or overwrite the content of the string, as it is immutable. This feature makes string objects unstable for storing secure information such as passwords, SSN, etc.
  • The data stored in string form will remain in memory until the garbage collector removes it. Due to the String Constant Pool (SCP), there is a significant chance that it will persist in memory for a long duration. Therefore, anyone with access to a memory dump can easily retrieve this information, which is another reason to avoid using strings for sensitive data.
  • If we notice in Java Swing applications, there is a method of JPasswordField, getPassword(), which returns char[] and the deprecated method getText() which returns the password in plain text. So Java itself recommends to use the getPassword() method.
  • Another reason for storing a password in char[] array, is because char[] can be sanitized. For example, after usage, one can override a clear password with junk, while a String is immutable in Java.

Example

The following Java program shows what happens when you convert a String into a char[] array.

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);
   }
}

Output

On running the above code, you will get a plain text and its corresponding char[] array. In the output given below, you can see char[] array is somewhat encrypted.

String Password is: string_pass_word
Character Password is: [C@6d06d69c
Updated on: 2025-05-20T19:16:27+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements