Open In App

final vs Immutability in Java

final: In Java, final is a modifier that is used for class, method, and variable also. When a variable is declared with the final keyword, its value can’t be modified, essentially, a constant. 
Immutability: In simple terms, immutability means unchanging overtime or being unable to be changed. In Java, we know that String objects are immutable means we can’t change anything to the existing String objects.

Differences between final and immutability






// Java program to illustrate
// difference between final
// and immutability
 
class Geeks {
    public static void main(String[] args)
    {
        final StringBuffer sb = new StringBuffer("Hello");
 
        // Even though reference variable sb is final
        // We can perform any changes
        sb.append("GFG");
 
        System.out.println(sb);
 
        // Here we will get Compile time error
        // Because reassignment is not possible for final variable
        sb = new StringBuffer("Hello World");
 
        System.out.println(sb);
    }
}

Output: 

Geeks.java:14: error: cannot assign a value to final variable sb
        sb = new StringBuffer("Hello World");
        ^
1 error

Pictorial Representation of the above Program



Explanation: In the above picture, we can see that we are creating an object of StringBuffer class by making reference final.

Article Tags :