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?

package org.arpit.java2blog.bean;
import java.util.ArrayList;

public final class Employee {

 private final String name;
 private final ArrayList<String> addresses;
 public Employee(String name, ArrayList<String> addresses) {
  super();
  this.name = name;
  ArrayList<String> tempAdd=new ArrayList<String>();
  for (int i = 0; i < addresses.size(); i++) {
   tempAdd.add(addresses.get(i));
  }
  this.addresses = tempAdd;
 }
 
 public String getName() {
  return name;
 }
 public ArrayList<String> getAddresses() {
  return addresses;
 } 
}
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.
public ArrayList<String> getAddresses() {
  return (ArrayList<String>) addresses.clone();
 }

4. Can you provide example of immutable class?

Answer  : Yes. I have created  Country class which is immutable.
package org.arpit.java2blog.bean;

import java.util.ArrayList;

public final class Country {
    // declared private final instance variable
 private final String countryName;
 // Mutable object
 private final ArrayList<String> listOfStates;

 public Country(String countryName, ArrayList<String> listOfStates) {
  super();
  this.countryName = countryName;
  // Creating deep copy for mutable object
  ArrayList<String> tempList = new ArrayList<String>();

  for (int i = 0; i < listOfStates.size(); i++) {
   tempList.add(listOfStates.get(i));
  }
  this.listOfStates = tempList;
 }

 public String getCountryName() {
     // Do not need to do cloning as it is immutable object
  return countryName;
 }

 public ArrayList<String> getListOfStates() {
     // Returning cloned object 
  return (ArrayList<String>) listOfStates.clone();
 }
}

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.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012