Saturday 3 January 2015

How to check whether String class is mutable or immutable programmatically in java

We can use hashCode() to check whether two string object have same hash code.
In this example, we have created a new String class object with value "Mutable".
Later, we have used  replace() to change the string str and resulting value is updated in str reference variable.
Now, if previous hashcode for str is equal to new hash code for str, then String class will be mutable otherwise it will be immutable.

public class StringMutable
{
    public static void main(String[] args)
{
String str = new String("Mutable");
int previousStrHashCode = str.hashCode();
str = str.replace('u', 'a');  // A new string object is created
int newHashCode = str.hashCode(); //  a new String object will have a new hashcode
System.out.println("prev "+previousStrHashCode + "   new : "+newHashCode );
if(previousStrHashCode == newHashCode)
{
System.out.println("Mutable");
}
else
{
System.out.println("Immutable");
}
}
}

Output:
prev -1216934138   new : -1789517158
Immutable

Here, hash code is different for string object before modification and after modification. Hence, a new object was created created instead of updating the previous String object.
This proves that String class is immutable. 



No comments:

Post a Comment