Why char array preferred over String for storing passwords in Java?

Arpit Bhatt
1 min readAug 24, 2021

String is immutable in Java and stored in the String pool. Once it’s created it stays in the pool until the garbage is collected, so even though we are done with the password it’s available in memory for a longer duration and there is no way to avoid it. It’s a security risk because anyone having access to a memory dump can find the password as clear text.

If we use a char array to store passwords, we can set it to blank once we are done with it. So we can control for how long it’s available in memory that avoids the security threat with String.

Notes:

  1. String is immutable where char is mutable.
  2. All Strings are stored in the String Constant Pool(SCP). And all Character arrays are stored in the Heap memory.
  3. String is not preferred for storing passwords but char is preferred for storing passwords

--

--