A String is immutable and may be interned, so once a password is in a String it stays in memory until the garbage collector removes it, which could be much later, and you can't erase it. A char[] can be overwritten with zeros as soon as you've finished with it, which shortens the time the password sits in memory.
Key Points: • Memory dumps, heap dumps and debugging tools can expose Strings that are still in memory. • You can clear a char[] with Arrays.fill(password, '\0'). A String can't be cleared. • Printing a char[] accidentally shows something like [C@6d06d69c rather than the password, so it is less likely to leak into logs. • Java's own APIs follow this: JPasswordField.getPassword() and Console.readPassword() return char[], and KeyStore uses char[] passwords. • It reduces risk but isn't a complete defence. Frameworks often convert passwords to Strings anyway, so also hash passwords with BCrypt and never log them.
Code Example:
import java.util.Arrays;
public class PasswordHandling {
static boolean check(char[] password) {
char[] expected = {'s', '3', 'c', 'r', 'e', 't'};
boolean ok = Arrays.equals(password, expected);
Arrays.fill(expected, '\0');
return ok;
}
public static void main(String[] args) {
char[] password = {'s', '3', 'c', 'r', 'e', 't'};
try {
System.out.println("Valid: " + check(password));
} finally {
Arrays.fill(password, '\0'); // wipe it from memory
}
System.out.println("After wipe: " + Arrays.toString(password).replace("\u0000", "0"));
String asString = "s3cret";
// There is no way to wipe asString; it stays until GC removes it
System.out.println("String printed by mistake: " + asString);
System.out.println("char[] printed by mistake starts with: "
+ String.valueOf((Object) password).substring(0, 3));
}
}Output:
Valid: true After wipe: [0, 0, 0, 0, 0, 0] String printed by mistake: s3cret char[] printed by mistake starts with: [C@
Good to Know: In a typical Spring Boot web application the password already arrives as a String from the HTTP request, so the char[] advice matters most in desktop tools, CLI programs and code that handles keys or certificates. In web apps, focus on HTTPS, hashing with BCrypt and keeping passwords out of logs.
Interview Tip: A concise interview answer is:
"A String is immutable and can't be cleared, so a password in a String stays in memory until garbage collection and could appear in a heap dump. A char[] can be wiped with Arrays.fill right after use, and printing it by mistake doesn't reveal the text. That's why APIs like Console.readPassword return char[], though it only reduces the risk, so I still hash passwords and never log them."
Previous question: Why is String a good choice for a HashMap key?
Next question: How does a switch statement on Strings work internally?