Immutability in Java

Immutability in Java

what is Immutability in Java ? What does immutable mean? Why it is being used? Lets learn it in this post.



Immutable means once we create we cannot changed its content.

Immutable object:

Once you create a object, you can’t modify the contents of that object.


— to make things thread safe so that no sync issues

— keys should be immutable — put — get 

— no need clone

— easy to construct,use and test


To create immutable class in java, we must  have to do following steps.

— all fields should be private and final

— class should be final so that no one can inherit

— methods should be final

–remove setter method

* if class with — user defined mutable object 

— then go to that class make all field private final — + removes setters 


 * class with — system defined mutable objects.. — inside domain class getter create new object and return ref with copied contents..



Final object then only reference cannot changed but data can be changed.

String Obj is Immutable in point ref..


final String — ref — cannot be changed…value can changes– string immutability property will not allow you change the value……. Immutable 


Immutable is thread safe because object is available for read only in term of immutable.


Why string and wrapper is immutable?

In wrapper class  

each wrapper class store a list of commonly used instances of own type in form of cache and whenever required, you can use them in your code. It helps in saving lots of byes in your program runtime.

Related Posts:

Singleton class in java

Inheritance Interview Question in java

Main Method Interview Question in java

Commonly asked programs in java interview