Immutable in Java

Java immutability
 

This articles focuses on the following :

  • What is meant by an Immutable class in Java ?
  • What is the advantage of an Immutable class ?
  • How to create an Immutable class ?
  • What happens when a variable or class is marked final ?

 

Immutability in Java

An object is considered immutable if its state cannot change after it is constructed. That means once the constructor of an Immutable class has completed execution, the created instance cannot be altered.

String class is immutable. So, the methods toUpperCase(), toLowerCase() etc on a String object don’t modify the same object.. The modifications happen on a new object.

Let’s look at the following code for this:

 

       
        String str = "Hello";
  str.toUpperCase();
  System.out.println(str);

If you run this code, it will NOT print “HELLO”, rather it will print the original value “Hello”

This is because a new String object is created when the method toUpperCase() is called on str and that contains the uppercase string.

To make it work, use the following code that reassigns the new instance reference to the original variable.

 

  String str = "Hello";
  str.toUpperCase();
  str = str.toUpperCase();
  System.out.println(str);

This program will print the uppercase string HELLO.

In contrast, StringBuilder class is mutable and modifications affect the same object.

 

Use of Immutability

Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state.

Immutability objects also don’t have the overhead if synchronization.

Since they are immutable, they can be cached and perform better compared to mutable counterparts. This is the reason why Strings are preferred as keys in hashmaps.

 

Guidelines for creating immutable class

Here are some guidelines if you are trying to create an immutable class:

Final fields

Make all fields final and private.

This will prevent any modification of the fields.

For example, the following code tries to change the value of an int variable and would throw a compilation error saying “final variable can not be reassigned”

  final int var = 10;
  var = 11;

setter Methods

Don’t provide setter methods for the properties.

Prevent overriding through sub-classes

You can declare the class as final. This would prevent altering base class functionality through overriding.

If any other class tries to subclass a final class, the compiler will complain saying “final class can not be subclassed”.

Another way of doing this is by making the constructor private and creating instances in factory methods.

Instance fields referring mutable objects

If the class has any mutable object fields, then don’t allow them to be changed. They must be defensively copied when they pass between the class and its caller.

 

Immutable class example

Here is an example of Immutable class.

final class ImmutableClass {
  
  private final String memberVariable;
  
  public String getMemberVariable() {
    return memberVariable;
  }

  public ImmutableClass(final String value){
    this.memberVariable = value;
  }
}

 

The field is a reference to an object(String) that is itself immutable.

The setter methods are absent. Also, the class has been marked final to prevent overriding that may alter immutability of parent class.

 

 

© 2015 – 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

One comment

Leave a Reply.. code can be added in <code> </code> tags

%d bloggers like this: