Appearance
Why is char[] preferred over String for passwords?
It is generally considered more secure to use a char[] array to store passwords because it can be wiped from memory more easily than a String object. When a String object is created in Java, it is immutable and stored on the heap. Because its contents cannot be modified, the password remains in memory until the garbage collector reclaims it. By contrast, a char[] array can be explicitly overwritten or zeroed out immediately after use:
java
char[] password = getPassword();
try {
// authenticate user
} finally {
Arrays.fill(password, '\0');
}This ensures sensitive data is cleared from memory as soon as it is no longer needed, reducing the window of exposure if the system is compromised. For modern applications, consider using dedicated security libraries or java.security.SecureString (Java 9+) for additional protection.