what is string literal?
it is a sequence of characters between quotations
what is string literal/constant pool?
Its a collection of references to string objects
String objects that have references from string constant pool live on heap memory
String s = "apple";
s is a variable in string constant pool referencing to string object "apple" that lives on heap
if I write
String s1 = "apple";
s1 is another variable in string constant pool that is referencing to same object "apple"
s.equals(s1) // will return true because equals checks contents of objects
s==s1//will also return true because equality operator checks for referential equality
String s = "mango";
Here, reference of variable s is changing from "apple" to "mango", but "apple" object is still present in heap memory. Hence, strings objects are Immutable(cannot be changed)
s.equals(s1);//will return false because now s is referencing to object "mango" and s1 is referencing to object "apple", which are 2 different objects
String object referenced from the string literal pool is created when the class is loaded
String literals are not eligible for garbage collection, the object is always reachable through the intern() method.