Immutable – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Tue, 26 Jan 2021 14:42:15 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Immutable – Java2Blog https://java2blog.com 32 32 Immutable class interview questions https://java2blog.com/immutable-class-interview-questions/?utm_source=rss&utm_medium=rss&utm_campaign=immutable-class-interview-questions https://java2blog.com/immutable-class-interview-questions/#comments Thu, 22 Dec 2016 18:39:00 +0000 http://www.java2blog.com/?p=29 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 addresses;
 public Employee(String name, ArrayList addresses) {
 super();
 this.name = name;
 ArrayList tempAdd=new ArrayList();
 for (int i = 0; i < addresses.size(); i++) {
 tempAdd.add(addresses.get(i));
 }
 this.addresses = tempAdd;
 }

 public String getName() {
 return name;
 }
 public ArrayList 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 getAddresses() {
  return (ArrayList) 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 listOfStates;

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

  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 getListOfStates() {
     // Returning cloned object 
  return (ArrayList) 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.
]]>
https://java2blog.com/immutable-class-interview-questions/feed/ 7
How to create immutable class in java https://java2blog.com/how-to-create-immutable-class-in-java/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-create-immutable-class-in-java https://java2blog.com/how-to-create-immutable-class-in-java/#comments Wed, 21 Dec 2016 18:26:00 +0000 http://www.java2blog.com/?p=30
In this tutorial, we are going to see how to create immutable class in java.
Immutable class is class whose state can not be changed once created.
Example: String is best example for immutable class. Once you create a String, you can not change it.
Immutable class is very simple to understand, it has only one state. Immutable class is carefully instantiated by the constructor. Immutable classes are thread safe. This is biggest advantage of immutable class, you don’t need to apply synchronization for immutable objects. Immutable class can be useful while putting object of immutable class in HashMap or it can be used for caching purpose because its value won’t change.

Immutable objects are by default thread safe.

Steps for creating a 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 imutable 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. I will explain this more in later part of this tutorial.

Read : Why String is immutable in java
Lets understand immutable class with a very simple example:
Lets create a simple class called Country.java.

public final class Country{

 private final String countryName; 
 private final ArrayList listOfStates;

 public Country(String countryName,ArrayList listOfStates) {
 super();
 this.countryName = countryName;
 this.listOfStates=listOfStates;

 }

 public String getCountryName() {
 return countryName;
 }

 public ArrayList getListOfStates() {
 return listOfStates;
 }

 public static void main(String args[])
 {
 ArrayList listOfStates=new ArrayList();
 listOfStates.add("Madhya Pradesh");
 listOfStates.add("Maharastra");
 listOfStates.add("Gujrat");

 Country country=new Country("India",listOfStates);
 System.out.println("Country : "+country.getCountryName());
 System.out.println("List of states : "+country.getListOfStates());
 // It will be added to the list because we did not use clone in getListOfStates
 country.getListOfStates().add("Kerala");
 // It will be added to the list because we did not use deep copy in constructor
 listOfStates.add("Rajasthan");
 System.out.println("Updated List of states : "+country.getListOfStates());

 } 
}

When you run the program, you will get below output:

Country : India
List of states : [Madhya Pradesh, Maharastra, Gujrat]
Updated List of states : [Madhya Pradesh, Maharastra, Gujrat, Kerala, Rajasthan]

Above class is not immutable. There are two reasons for it :

  • We did not use clone in getListOfStates() method, so we are able to add “Kerala” to the listOfStates.
  • We did not do deep copy for listOfStates , so we are able to add “Rajasthan” to the list.
Lets use clone in getListOfStates() method and see the difference, just change getListOfStates() to below code:
public ArrayList getListOfStates() {
  return  (ArrayList) listOfStates.clone();
 }
when you run the program after making above changes, you will get below output:
Country : India
List of states : [Madhya Pradesh, Maharastra, Gujrat]
Updated List of states : [Madhya Pradesh, Maharastra, Gujrat, Rajasthan]
If you notice, “Kerala” is not added to the list because we are returning clone of listOfStates in getListOfStates() method, so adding “Kerala” to country.getListOfStates() won’t affect original list.
We are one step closed to immutable class now. 
Lets change constructor to make deep copy of listOfStates object.
public Country(String countryName, ArrayList listOfStates) {
  super();
  this.countryName = countryName;
  ArrayList tempList = new ArrayList();

  for (int i = 0; i < listOfStates.size(); i++) {
   tempList.add(listOfStates.get(i));
  }
  this.listOfStates = tempList;
 }
Lets check the final class which we have created after doing above changes.
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 listOfStates;

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

  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 getListOfStates() {
     // Returning cloned object 
  return (ArrayList) listOfStates.clone();
 }

 public static void main(String args[]) {
  ArrayList listOfStates = new ArrayList();
  listOfStates.add("Madhya Pradesh");
  listOfStates.add("Maharastra");
  listOfStates.add("Gujrat");
  String countryName="India";
  Country country = new Country(countryName, listOfStates);
  System.out.println("Country : " + country.getCountryName());
  // Lets try to change local variable countryName
  countryName="China";
  System.out.println("Updated Country : " + country.getCountryName());
  System.out.println("List of states : " + country.getListOfStates());
  // It will  not be added to the list because we are using clone in
  // getListOfStates
  country.getListOfStates().add("Kerala");
  // It will not be added to the list because we are using deep copy in
  // constructor
  listOfStates.add("Rajasthan");
  System.out.println("Updated List of states : " + country.getListOfStates());

 }

}
When you run above program, you will get below output:
Country : India
Updated Country : India
List of states : [Madhya Pradesh, Maharastra, Gujrat]
Updated List of states : [Madhya Pradesh, Maharastra, Gujrat]
Country class is immutable class now. As you can see, we are doing deep copy for listOfStates, so “Rajasthan” will not be added to the listOfStates.

I hope it will help you to create immutable class in java.

]]>
https://java2blog.com/how-to-create-immutable-class-in-java/feed/ 1
Why String is immutable in java https://java2blog.com/why-string-is-immutable-in-java/?utm_source=rss&utm_medium=rss&utm_campaign=why-string-is-immutable-in-java https://java2blog.com/why-string-is-immutable-in-java/#respond Sat, 07 May 2016 21:01:00 +0000 http://www.java2blog.com/?p=223
String class is immutable in java. If you take dictionary meaning of immutable, it means unable to be changed or unchanging over time, so String is unchangeable or unmodifiable in java.
Let’s understand with example.
String str1="Hello";
str1.concat("java2blog");
System.out.println(str1);

// Output will be 
Hello
As you can see, value of str1 did not change. It created another String object with value “Hellojava2blog” but did not change String str1

This explains that String is immutable in nature.

Now let’s understand what are potential reasons to make string immutable in java

String pool :

If you simply assign a Value to String using double quotes, it is stored in area called string literal pool and one string can be referenced by many reference variables and if String Is mutable,  then it will affect all reference variables.

Thread safe :

Immutable objects are by default thread safe,  so you don’t need to put synchronisation for it and String instance can be safely shared among multiple threads.

Security :

If String is not immutable then it may cause multiple security issue.
For example, while connecting to database,  you provide username, password, Port and host name etc as String,  if String is mutable, any hacker can change the reference value and cause security threats to application.

Cache hash value :

When you use String as key in HashMap or HashSet or any other collection,  you can cache it’s hash value.  As String is immutable in nature, you don’t need to calculate each time as it will be constant. It greatly improve performance for this hash based collections.

Class loading :

String is used as class loading mechanism.  It is passed as a parameter.  If String is mutable,  it is a security threat as any hacker could have changed it.

]]>
https://java2blog.com/why-string-is-immutable-in-java/feed/ 0