Mutability & Immutability In Java

Mutability & Immutability In Java

In Java, classes can be mutable or immutable. But what does it mean by mutable or immutable? Let us try to understand it by step-by-step explanation. Here, we are going to cover –

  • What is mutability?
  • What is immutability?
  • Create your own immutable class
  • What is the difference between immutable & final?
  • Conclusion

 

What is mutability?

The word mutable means changeable. If an object of a class can be changed, then this class is called mutable class. In simple words, if you can change/update the values of an object without creating another object then it’s mutability.

For example, StringBuffer is a mutable class. Let us take a look at it –

Step 1:

StringBuffer sb = new StringBuffer(“codemeright”);

Here, JVM creates a new object of StringBuffer class in memory.

Step 2:

sb.append(“.com”);

Here, the object gets updated by appending  ‘.com’ in the ‘codemeright’ which makes it ‘codemeright.com’

 

What is immutability?

The word immutable means unchangeable. If an object of a class cannot be changed, then this class is called immutable class. In simple words, if you can’t change/update the values of an object without creating another object then it's immutability.

If we try to change an object of an immutable class, then a new object with the changed value is created.

For example, String is an immutable class. Let us take a look at it –

Step 1:

String s = new String(“codemeright”);

Here, JVM creates a new object of String class in memory.

Step 2:

s.concat(“.com”);

Here, JVM creates a new object with “codemeright.com” and assigns to this new object. The object with the value “codemeright” becomes eligible for garbage collection.

 

Create your own immutable class

You can create your own immutable class implementing each method in that class as shown below. Every time the value of the object gets changed the method returns a new object with that value.

package com.codemeright.immutable;

public class Test {

    private int val;

    public Test(int val) {

        this.val = val;

    }

    //This function is giving the Test class immutable nature

    public Test setVal(int val) {

        if(this.val == val) {

            this.val = val;

            return this;

        } else {

            return new Test(val);

        }

    }

}

What is the difference between immutable and final?

As you know by now that immutable means unchangeable. But, final also means unchangeable. So, Are they same? No, immutability is related to object and final is related to variables. Let's try to understand it with examples - 

 

Immutable

Immutable is related to objects. Immutable means the object cannot be changed. But the variable can be reinitialized.

For example –

 

Step 1:

Let's create an object on immutable class String s and initialize it with the value 'codemeright'

String s = new String(“codemeright”);

System.out.println(s);

OUTPUT

codemeright

 

Step 2:

Now, concat '.com' in the previous value 'codemeright' of object s. This will create a new object with the value 'codemeright.com' due to immutable nature of the String class and the object s will remain the same. So, now if you try to print object s, it will still print the old value 'codemeright'. 

s.concat(“.com”);       

// This creates a new object and we are not assigning it to any variable. Hence, that object will become eligible for garbage collection. Optionally we can assign it as String s2 = s.concat('.com'); Then, s2 will print 'codemeright.com'

System.out.println(s); 

OUTPUT

codemeright

 

Step 3:

Again, try to reinitialize the variable s with a new String object containing our required value 'codemeright.com'. This is possible because the variable s has not been declared as final. It means it can be reinitialized as many times as we want. So, now if we try to print the variable s then it will print 'codemeright.com'.

s = new String(codemeright.com);

System.out.println(s); 

OUTPUT

codemeright.com

 

Final

If a variable is declared as final then that variable cannot be reinitialized. It means we cannot assign a new object to that variable. But we can change the existing object. Hence, it's not same as immutable classes.

For example –

 

Step 1:

Let's create an object of StringBuffer class and declare it as final.

final StringBuffer sb = new StringBuffer(“codemeright”);

System.out.println(sb);

OUTPUT:

codemeright

 

Step 2:

Now, try to change the value of the object by appending '.com' in the current value. This is possible because final does not apply immutability (No change in the object). So, when we print our object sb after appending '.com' then it will print 'codemeright.com'. Hence, the object is changed.

sb.append(“.com”);

System.out.println(sb); 

OUTPUT:

'codemeright.com'

 

Step 3:

Again, try to reassign the variable sb with same or different value. This will generate compile time error because a variable declared as final cannot be reinitialized. 

sb = new StringBuffer(“codemeright.com”); //ERROR

 

Conclusion

So, in a nutshell, objects of mutable classes can be changed and objects of immutable classes cannot be changed. If we try to change the object of an immutable class, then a new object with changed value gets created. We can create our own immutable classes implementing each method in that class in a way that those methods return a new object, every time we try to change the values of that object.

FOLLOW US ON