Why is a char array recommended over String for storing passwords in Java?
A String is immutable and may stay in memory until garbage collection, so it cannot be wiped. A char array can be overwritten with blanks right after use, which shrinks the time a password sits in memory where a heap dump could expose it.
Explain it simply
Writing your PIN on a sticky note that you cannot erase, only throw away someday, is risky. A char array is a whiteboard: you use it, then wipe it straight away. A String is the sticky note that lingers.
Example
char[] password = {'s', 'e', 'c', 'r', 'e', 't'};
// ... verify the password ...
java.util.Arrays.fill(password, '*'); // wipe immediately
System.out.println(new String(password)); // prints: ******What to say in the interview
"Strings are immutable, so a password in a String stays in the heap, and possibly the string pool, until the garbage collector decides to remove it, and I have no way to overwrite it. A char array can be zeroed as soon as I am done. That is why Swing's JPasswordField and Console.readPassword return char[]. It is also easy to log a String by accident, while printing a char array shows only a reference."
Common mistakes
- Converting the char array to a String for convenience, which undoes the benefit.
- Claiming this makes the app fully secure. It only narrows the window of exposure.