What is the difference between immutable and final in java?

final means that you can't change the object's reference to point to another reference or another object, but you can still mutate its state (using setter methods e.g). Where immutable means that the object's actual value can't be changed, but you can change its reference to another one.

Concerning the second part of your question (immutability part), the compiler creates a new String object with the value of "Sam", and points the name reference to it.


final ensure that the address of the object remains the same. Where as the Immutable suggests that we can't change the state of the object once created.

final is just a keyword whereas Immutable is a pattern.

In Case of your first question you have marked the variable as final, which means you would not be able to change the memory address of it and can't assign a value once more.

In case of your second question Immutable ensures you can't change the state of the object you have created.

Tags:

Java