Top Java Immutable Class frequently asked interview questions
In this post we will look at Java Immutable Class Interview questions. Examples are provided with explanation.
Q: What is meant by immutable in Java?
A: Immutable means that for a given object once execution of the constructor has finished it cannot be modified. For immutable objects the internal fields cannot be modified.
Q: Why is String immutable in Java?
A: The advantages of having String immutable in Java is as follows-
- Security - This is one of the major reasons for making String immutable. We need immutable string parameters for credentials, network connections, database connections. Such parameters should never be modified so these should be immutable.
- Multithreading concurrency - In a multithreaded application synchronization issues are resolved as Strings are immutable
- Caching - Since String is immutable, its hashcode is cached at the time of creation and it does not need to be calculated again. So it can be used as key in hashmap.
- String Pool - Since String is immutable, there is a concept of String pool in java. So strings can be reused.
- Class loading - Strings are used in java classloader and immutability provides security that correct class is getting loaded by Classloader.
A: The following Java Classes are immutable-