Q1. What is an Immutable Object ?
Ans. Object that can't be changed after instantiation.
Q2. What is an immutable class ?
Ans. Class using which only immutable (objects that cannot be changed after initialization) objects can be created.
Q3. 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.
3. Security
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.
Q4. How to implement an immutable class ?
Ans. We can make a class immutable by
1. Making all methods and variables as private.
2. Setting variables within constructor.
Public Class ImmutableClass{
private int member;
ImmutableClass(int var){
member=var;
}
}
and then we can initialize the object of the class as
ImmutableClass immutableObject = new ImmutableClass(5);
Now all members being private , you can't change the state of the object.
Q5. Does Declaring an object "final" makes it immutable ?
Ans. Only declaring primitive types as final makes them immutable. Making objects final means that the object handler cannot be used to target some other object but the object is still mutable.
Q6. 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.
Q7. Why String is popular HashMap key in Java?
Ans. Since String is immutable, its hashcode is cached at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for key in a Map and it’s processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.