Understanding String and String literals in Java

In any programming language String is an important data structure. In this post we will explore about String in Java.
String is a class which represents the characters. Being a class it provides many methods to work with a String. To create a String in Java we have two different ways and they are 
  1. String x = "Hello";
  2. String a = new String("Hello");
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. )

Memory Allocation of String in memory understanding

The same can be demonstrated by program. Refer following program and its output which shows the above concept.

Java Program and Output for String and String literals

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.