Advertisement
Advanced Java, Java Fundamentals: Syntax, Data Types & Operators

How does Java's String immutability, combined with the string pool, interact with security-sensitive code (like handling passwords), and why is char[] generally recommended over String for storing sensitive data temporarily in memory?

Short answer

Since String is immutable, once created, its underlying character data cannot be explicitly cleared or overwritten -- a String containing a sensitive value (like a password) will remain in memory in its original, unmodified form for as long as the garbage collector happens to…

Save Java mock interview
Advertisement
AModel answer
Since String is immutable, once created, its underlying character data cannot be explicitly cleared or overwritten -- a String containing a sensitive value (like a password) will remain in memory in its original, unmodified form for as long as the garbage collector happens to keep that String object alive (which could be an unpredictable, potentially lengthy duration, and the memory might even be paged to disk via OS-level swapping before being collected, potentially persisting the sensitive value beyond the process's own lifetime) -- a mutable char[] array, by contrast, CAN be explicitly overwritten (zeroed out) immediately after use (Arrays.fill(passwordChars, '0')), proactively minimizing the window during which the sensitive value remains recoverable in memory, which is why security-conscious APIs (like many JDBC drivers' password parameters, and Java's own Console.readPassword()) deliberately use char[] rather than String for this specific purpose.
// Less secure: String is immutable, can't be explicitly cleared, and might linger in the string pool
String password = new String(passwordChars);  // creates an uncontrollable, un-clearable copy

// More secure: char[] can be explicitly zeroed out immediately after use
char[] passwordChars = console.readPassword("Enter password: ");
try {
    authenticateUser(passwordChars);
} finally {
    Arrays.fill(passwordChars, '0');  // proactively overwrite the sensitive data in memory
}
Real-world example
A security-conscious login handler reads a user's password into a char[] via Console.readPassword() rather than accepting it as a String, explicitly zeroing out the array immediately after the authentication attempt completes, reducing (though not eliminating entirely, since a String-based representation may still exist transiently elsewhere, like within the authentication library itself) the window during which the plaintext password value remains recoverable from a memory dump.
Likely follow-ups
  • Does this char[] approach genuinely eliminate all risk of the sensitive value being recoverable from memory, given the JVM/GC's own internal behavior?
  • Why does the string pool specifically make String an even worse choice for sensitive data beyond just its basic immutability?
Related topics