NotesOfAj
One thing we need to understand before jumping in to String Pool concept is String Immutability. We all know String is immutable.
Mutable - An Object called Mutable when its state can be changed dynamically.
Immutable - An Object called Immutable when its state is constant always.
Because String is Immutable the String Pool concept is possible. You can imagine the String Pool as a set of Strings in a pool or pool of Strings. There are few advantages of String Pool concept. Assume there are two String objects s1 and s2 with values Sugar and Sweet, there will be two entries made into the String Pool. Now assume there is a third String s3 has been created with a value Sweet, this time there will not be any entry in the String Pool. This is because String Pool already has the value Sweet, the third String object s3 will refer to this value from the String Pool. This saves space in Java Heap Space.
String s1= "Sugar";
String s2 = "Sweet";
String s3 = "Sweet";
However if we try to create a String using new operator, the reference will be created in Java heap space and in String Pool as well. The object in String Pool will be created only when there is no reference to the same object in String Pool.
String s4 = new String("Salt");
Here the string s4 value is Salt, in this case the object will be created both in the Java Heap and String Pool as well, as there is reference to Salt object in the String Pool.
String s5 = new String("Sugar");
In this case the object will for s5 will be created only in the Java Heap Space as the same object is already available in String Pool.
We will discuss more about Java Heap Space and String Pool inside the Java Heap Space later in other notes.