Monday, February 12, 2018

Can we create a immutable class without marking it as final?

For creating immutable class it is not mandatory to mark the class as final.

Let me take one of such example from java classes itself "BigInteger" class is immutable but its not final.

Actually Immutability is a concept according to which ones the object created then it can not be modified.
Let's think from JVM point of view, from JVM point of view all threads must share the same copy of the object and it is fully constructed before any thread accesses it and the state of the object doesn't change after its construction.
Immutability means there is no way to change the state of the object once it is created and this is achieved by three thumb rules which makes the compiler to recognize that class is immutable and they are as follows :-
1) all non private fields should be final
2) make sure there is no method in the class that can change the fields of the object either directly or indirectly
3) any object reference defined in the class can't be modified outside from the class.

private static void testBigIntegerImmutability(){
BigInteger sum = new BigInteger("1");
for(int i=0; i<=10;i++){
sum.add(BigInteger.valueOf(i));
}
System.out.println(sum);
}

Saturday, October 3, 2009

HIIIIIIIIIII
HI FRIENDS ARPIT HERE
I WANT TO SHARE MY SWEET MEMORIES IN MY UNIVERSITY NAME -MANGALAYATAN UNIVERSITY.
ITS MY FIRST DAY IN MY UNIVERSITY LIFE AFTER DOING MY 12 WITH 73% MARKS.
AS I ENTERED IN THE UNIVERSITY CAMPUS I WAS WORRIED ABOUT RAGGING BUT IT WAS MY FIRST BATCH SO I WAS NOT WORRIED ABOUT IT......