Avatar ·

Why is char[] preferred over String for storing passwords in Java?

Hi everyone! I'm a beginner Java developer writing a small user authentication application. I've encountered a security question when working with passwords.\n\nUsually I use String to input a password from the console or from a JPasswordField. For example:\n\n```java\nConsole console = System.console();\nString password = new String(console.readPassword("Enter password: "));\n```\n\nBut recently on a forum I read that using String for passwords is bad practice, and it's better to use char[]. Honestly, I don't quite understand the difference. After all, String is just a set of characters, just like a char array. Why is char[] considered safer?\n\nI understand that String is immutable, but is that a problem? After using the password, I can just assign the variable to null, and the garbage collector will eventually remove it from memory. But with a char array, I can manually overwrite each element after use. Is that the only difference? Or are there other reasons?\n\nI would be grateful for an explanation and maybe some code examples of how to properly work with char[] for passwords. Thanks in advance!