8/15/15

Immutability in Java


Immutability in Java


Readers, first we will see little about wrapper classes in Java.
Many of us know that java is not all objects, there are some primitives also. 

Primitives in java are :-  byte, short, int, float, long, double, char, boolean 

And java has two types of data types
1. Primitive
2. Reference type (Objects)

These primitives are coming from the native languages(C).
Above things are a bit distraction but important to know. 
In Java to have everything like objects, wrapper classes are there to wrap around a primitive type and make it an object. 
Surprisingly all these wrapper classes are immutable. Yes sir/madam they are.

Immutability says if i am created once then you can not change me. If you want to make any change in me then you need to use me and create something else. 
For example :-

String s1 = new String("abc");

and now you want to make

s1.concat("def");

"abc" is create and assigned to s1 and it will be like this. If you want to make change and concat "def" in that. "abc" will remain as it is, new "abcdef" will be created because of immutability.
So if a string is created it will not be modified. you can create a new string to get something new out of it.

So there is immutability in root level of Java as you have seen and so it is important behaviour.

Why we make immutable class as final

Immutability is in deep roots of java. So you are not suppose to temper with immutability.
If i don't want to temper or alter my class then in java i can make it final and stop you from distorting java at root level.


If you are allowed to remove Immutability

This will be really a disaster. Suppose you have used string in entire application  assuming once created it will not changed. Now if i say that behaviour is gone, your application will collapse badly.


And yes you can create your own immutable classes.