Why is char preferred over String for passwords?
Due to the immutability of Strings, their contents cannot be altered, as any modification would result in a new String object. Once a String object is created and you later decide to change the password, there is no means to empty the string. The only possibility is to render the string eligible for garbage collection. Since Strings are utilized in the String pool for reusability, there is a significant likelihood that they will persist in memory for an extended period, which poses a security risk.
On the other hand, with a char, you have the ability to explicitly erase the data once you have finished using it. You can overwrite the array with any value of your choosing, ensuring that the password will not exist anywhere in the system, even prior to garbage collection.
Java itself advises the use of the getPassword() method of JPasswordField, which returns a char, while deprecating the getText() method, which returns the password in clear text, citing security reasons. It is advisable to heed the guidance of the Java team and adhere to established standards, rather than going against them.
Why String is immutable in Java ?
The term "Mutable" denotes the characteristic of an entity being susceptible to change, while "Immutable" signifies the opposite, indicating that the entity is inherently resistant to modification. In the context of objects, an Immutable Object refers to an entity whose state remains unalterable following its creation. Regarding Strings specifically, their immutability denotes that it is not possible to modify the object itself, but it is feasible to modify the reference pointing to the object.
When we describe an object as immutable, we imply that its fundamental attributes, or its internal state, cannot be modified once it has been instantiated. This immutability provides several advantages, including improved predictability, enhanced thread safety, and simplification of concurrent programming. Immutable objects ensure that their values remain constant throughout their existence, eliminating concerns related to accidental modifications or unexpected behavior caused by external factors.
Returning to the specific case of Strings, their immutability is a fundamental characteristic of the Java programming language. Although you cannot alter the content of a String object directly, it is essential to recognize that you can create a new String object with a modified value and assign it to a different reference. This behavior stems from the fact that Strings in Java are implemented as objects rather than primitive data types, and their immutability serves as a means to uphold data integrity and preserve memory efficiency.