Why String is immutable in java ?
In this article, we will learn why string is immutable in java, jumping into the topic →String is the public final class present in the java.lang package.
We can create string objects in two ways :
- Using String literals
- Using new keyword
Once the string objects gets created it is stored in the memory called as string pool which contains a string constant pool and string non-constant pool.
String objects which are created using the literals are stored in the constant pool where constant pool wont allow duplicates.
String objects which are created using the new keyword are stored in the non-constant pool where non-constant pool allow duplicates.
Now let us understand why string is immutable in steps :
Now we will create an object of the string using the literals (common way).so when we create the object of the string it is stored in the memory nothing but string pool.
String str="hello";
System.out.println(System.identityHashCode(str)); //798154996
So now we want to know the memory locations of the object which we have created so in the above code we have printed the hashcode of that object.
Next we will create another string object with same value as it will aslo be stored in the string pool
String str="hello";
System.out.println(System.identityHashCode(str)); //798154996
String str1="hello";
System.out.println(System.identityHashCode(str1)); //798154996
Now you might be wondering why both the string objects has the same hashcode (means that they both are pointing to the same memory locations). because these two objects are created using the literals where it store the string objects in the constant pool where duplication is not allowed as we have same value or content for both.
Now we will create two string objects using the new keyword and we will print the hashcode of that two objects.
String str=new String("hello");
String str1=new String("hello");
System.out.println(System.identityHashCode(str)); //798154996
System.out.println(System.identityHashCode(str1)); //681842940
As we observe that we have two different hashcode that means these two objects are pointing to the different memory locations. Because these two objects are created using the new keyword so they are stored in the non-constant pool where duplicates are allowed.
These is the reason why we get false when we try to compare the two string objects also when we have the same value.
That’s all for this article. Hope you have enjoyed this article :)
Thank you