Why String is an immutable class in Java ?
Before going for the above question we should be clear what are Immutable classes ?
Immutable classes are the one which once created, then its instances can not be changed. Objects of the Immutable class are the objects whose state can not be changed. We can define any class as immutable by adding keyword final before the class definition.
The String pool is special storage area used for the Strings allocation. If a String is created it will refer to String pool if it already exists there it will return the same string reference.
For Example:
String string1 = "xyz";
String string2 = "xyz";
Here in the above code as both the objects are referring to the same string they will return the same String pool reference.
So, comparing the both objects (string1 == string2) will give the true result as both refer to the same String pool. But if objects are initialized with different pool they will return false
For Example :
String string1 = new String "xyz";
String string2 = new String "xyz";
Now both the object are referring to the different String pool as new keyword has initialized different new String pools for both the objects.
So, on comparing (string1 == string2) we will get the false result as both the object are returning different pool's Strings.
0 Comment(s)