Immutable String in Java
Immutable simply means unmodifiable or unchangeable.
Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code.
Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state.
String object is considered immutable if its state cannot change after it is constructed. If we try to change the state, new String object will be created.
String Pool is possible only because String is immutable in Java and its implementation of String interning concept (string interning is a method of storing only one copy of each distinct string value, which must be immutable).
In the above image,
String s1=” Karnan”;
for this statement first, java will check “karnan” string available or not in the string pool. If it is not then creating an object and pointing that reference to s1 variable.
String s2=” Karnan”;
for this statement first, java will check the “karnan” value in string pool. It is already there so assigning the previous created object reference to s2 variable now s1 & s2 are pointing same object in the string pool.
String s3 = new String(“karnan”);
In this statement, we force String class to create a new String object in heap space using new operator. So new string object will be created in the heap area and pointing that reference to s3 variable.
“==” operator compares the two objects on their physical address.
s1==s2; is always true
Get Karnan Sooriyakumar’s stories in your inbox
Join Medium for free to get updates from this writer.
s2==s3; is always false
public class Test {public static void main(String[] args) {String s1= "karnan";String s2= "karnan";String s3 = new String("karnan");System.out.println(s1==s2);System.out.println(s2==s3);}}
--------------------------------------------------------------------Outputtruefalse







