Check String Class is Immutable

Run the following code in some Java main class.

String test = "Test";
System.out.println(test.hashCode());
test="Immutable";
System.out.println(test.hashCode());
test=test.concat("Concat");
System.out.println(test.hashCode());
System.out.println(test);


Here we can see that for every hashCode() method  a new Hash Code is generated which shows whenever we are referring to test variable a new string is created in a different location.

But in the last when we have used concat method it is printing both the values whoch shows the object remains the same only value is added to it.





Comments

Popular Posts