Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between immutable and final in java?

Tags:

java

I was recently asked this quesion. But was not able to explain concisely what exactly sets both these concepts apart.

For example

Final and Immutable:

final String name = "John"; 

if I now write

name = "Sam"; 

I will get a compiler error

Immutable:

String name = "John"; name = "Sam";  

it works.

I think this explains a part of it in application. But can I get a good, easy to understand explanation on both these topic?

like image 388
nanospeck Avatar asked Dec 04 '15 11:12

nanospeck


1 Answers

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.

like image 108
Mohammed Aouf Zouag Avatar answered Sep 22 '22 19:09

Mohammed Aouf Zouag