Search Tutorials


Top Java Immutable Class (2024) frequently asked interview questions | JavaInUse

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.
Q: Which Java built in classes are immutable?
A:
The following Java Classes are immutable-
  • String
  • Integer
  • Boolean
  • Character
  • Byte
  • Short
  • Long
  • Float
  • Double
  • BigDecimal
  • BigInteger

Q: How to make an object immutable?
A:
Objects can be made immutable as follows -
  • The Class must be declared as final so that it cannot be subclassed and its methods cannot be overridden
  • All the class members must be declared as final so that once the object is created it's value cannot be changed
  • For all the class members define getters.
  • Do not define any setter methods for class members

Q: What are the advantages of making objects immutable in Java?
A: