Q1. Why is String immutable in Java ?
Ans. 1. String Pool
When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object. If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.
2. To Cache its Hashcode
If string is not immutable, One can change its hashcode and hence not fit to be cached.
String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Making it mutable might possess threats due to interception by the other code segment.
Q2. Why Char array is preferred over String for storing password?
Ans. String is immutable in java and stored in String pool. Once it’s created it stays in the pool until unless garbage collected, so even though we are done with password it’s available in memory for longer duration and there is no way to avoid it. It’s a security risk because anyone having access to memory dump can find the password as clear text.