Immutable class interview questions

Immutable class interview questions
In this post, I am going to share java interview questions which are generally asked on immutable class. Immutable class is important topic as it deals with creation of thread safe class.
Here I am providing some important immutable class interview questions with answers.

1. What is immutable class?

Answer : Immutable objects are those objects whose state can not be changed once created. Class whose objects possess this characteristic can be termed as immutable class.
For example : String , Integer.

2. What are steps for creating an immutable class?

  • Make your class final : 
    If you make your class final, no class will be able to extend it, hence will not be able override methods of this class.
  • Declare all instance variable with private and final : 
    If you make instance variable private, no outside class will be able to access instance variables and if you make them final, you can not change it.
  • Say no to setter methods :
    Don’t create setter method for any instance variables, hence there will be no explicit way to change state of instance variables.
  • Initialize all variables in constructor :
    You can initialize variables in constructor. You need to take special care while working with mutable object. You need to do deep copy in case of immutable objects.
  • Perform cloning of mutable objects while returning from getter method:
    If you return clone of object from getter method, it won’t return original object, so your original object will remain intact.
    Read : Why String is immutable in java

3. Can you answer if below Employee class is immutable or not? If not what will you do to make it immutable?

Answer: 

Employee class is not an immutable class because you can still perform employee.getAddresses().add(“New address”) and it will be added to employee’s addresses list.
You need to return clone of addresses list from getAddresses method ,so employee.getAddresses().add(“New address”)  won’t impact employee’s addresses list.
If you change above getAddresses() method to below method, Employee class will become immutable.

4. Can you provide example of immutable class?

Answer  : Yes. I have created  Country class which is immutable.

5. Do immutable classes thread safe? If yes then how?

Answer : 
Immutable classes are thread safe because you can not change state of immutable objects, so even if two thread access immutable object in parallel, it won’t create any issue.

6. What precautions you need to take if you are working with mutable instance variables?

If you are working with mutable instance variable(addresses list in above Employee class) then do following:

  • Do deep copy mutable variable in constructor.
  • Return clone of instance variable from getter of that instance variable rather than actual variable.
You can read more about it at how to create immutable class in java.

7. Why immutable objects are considered to be good keys for HashMap?

Answer : Immutable object’s hashcode won’t change, so it makes key retrieval faster as you can cache different hashcode for different keys. In case of mutable object, hashcode may be dependent on mutable fields, if any value for these field changes, it might change hashcode, so you might not able to find your key in HashMap as hashcode is different now.

8. Can you give some good examples of immutable classes?

String, Integer, Long, Double, Character, Boolean etc and much more. Date is not an immutable class.

Related Posts

  • Hibernate interview questions
    16 April

    Top 40+ Hibernate interview questions and answers

    Table of Contents1. What is ORM?2. What is Hibernate?3. What are advantages of Hibernate?4. Explain architecture of Hibernate?5. What are some core interfaces of hibernate?6. Explain brief about Session interface used in hibernate?7. Are session objects thread safe?8. Explain brief about SessionFactory object used in hibernate?9. What is Configuration class in hibernate?10. Explain brief about […]

  • Java Interview questions
    22 May

    Java interview questions

    Table of ContentsCore JavaCore java interview questionsCollections interview questionsMultithreading interview questionsJava 8 interview questionsOOPs interview questionsException Handling interview questionsString interview questionsSerialization interview questionsmethod overloading and method overriding interview questionsImmutable class interview questionsJava tricky interview questions Basic interview questions for fresher Interview questions for 5 to 7 years experiencedHow HashMap works in java? Difference between Interface […]

  • Solid principles in java
    09 November

    SOLID Principles in Java

    Table of ContentsWhat is the meaning of S.O.L.I.D?Single Responsibility Principle (SRP)Open Closed Principle Liskov Substitution Principle Interface Segregation PrincipleDependency Inversion PrincipleWrap Up In this post, we will see 5 SOLID Principles in Java. Robert C. Martin gave five objected oriented design principles, and the acronym S.O.L.I.D is used for it. Each letter of this acronym […]

  • Java interview questions for 2 years experience
    08 November

    Java interview questions for 2 years experience

    Table of Contents1.   Can we override static method in java?2.   Can you overload main method in java?3. Can we override private methods in java?4. What is the base class for all the classes?5.   Can you list down some of important method from object class?6.   Which two methods should you override while putting the custom object as […]

  • Java interview questions for 5 years experience
    08 November

    Java interview questions for 5 years experience

    Table of Contents1. Guess the output of below program.2. Guess the output of below program.3. Guess the output of below program.4. What will happen in case of below program?5. What will happen in case of below program?6. What will happen in case of below program?7. Guess the output of below program.8. Guess the output of […]

  • Java tricky interview questions
    11 September

    Java technical interview questions

    Table of Contents1 How HashMap works in java?2 Which methods you should implement for key Object in HashMap?3. Guess the output of below program.4. Guess the output of below code.5. What are differences between Comparator and Comparable?6. What is difference between Error and Exception?7. What is ClassLoader in java?8. What are types of ClassLoader in java?9. […]

Comments

  1. Hi Arpit, great article. Should you use also clone() for deep copy of arraylist ? For this line:
    tempList.add(listOfStates.get(i))? Or you are assuming that list is a list of Strings? Thanks

    1. Hi Goran,
      I am assuming that list is a list of Strings. As String is immutable in java, you don’t need to use deep copy for ArrayList.
      Thank you!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.