Interview Q&A / Java

IntermediateQuick answer1 min readUpdated 3 Oct 2026

Why is a char array recommended over String for storing passwords in Java?

SHORT ANSWER

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

java
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.

#java#strings#security

Related questions

Practise more Java questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Java quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.