First approach is to assign literal value to instance of String x. In this case we need to understand that Java maintains a pool of constants and which will not store any duplicate value. In case of duplication same value will be shared between the instances of String.
Second approach is to create a String using new operator. New operator will allocate memory dynamically and returns the reference. In this case the heap memory will be used. Every call to new will create a new memory regardless of content.
Consider following four statements :
String x = “Hello”;
String y = “Hello”;
String a = new String(“Hello”);
String b = new String(“Hello”);
In the above case, x and y refers to same memory in constant pool and hence x==y will return true as they have same reference. In case of a and b, both have different reference and hence a==b will return false as they refers to different memory locations. Following diagram clears more about x,y, a and b.
(NOTE == operator compare reference and equals method is used to check for equality in Reference type. )
In both ways String is immutable i.e. once created its values never changes. Every change will create new String internally. So mostly all methods that changes the String will return the new String.