Java – String
An array or sequence of characters is known as a string. But Java handles string as an object of type String.
In Java, String is as immutable object. That is once it is created, it cannot be changed.
If we try to change a String object, a new String object is created, and original String object is left unchanged.
Now we have tried to prove it with two different scenarios as shown below:
If we want to create a string that can be changed, then we should create it using StringBuffer & StringBuilder (explained later in detail).
There are two techniques to create a string object
1) Using string literal
2) Using new keyword
When a String object is created using a string literal, the String object is stored in the String Constant Pool (SCP).
When a String object is created using the new operator, it is stored in the heap area (outside SCP) as well as inside string constant pool.
What is String Constant Pool?
The String Constant Pool (SCP) is a place where objects with string literals are stored.
It is a part of the heap memory area.
1) Creating a string object using string literal
While creating String object using string literal, new operator is not used.
String objects can be created using string literal as shown below:
String str1 = “James”;
Using a string literal, the String object is created only in String Constant Pool (SCP), as shown below:
2) Creating a String object using new keyword
When String object is created using the new keyword, two same string objects are created. One in heap area (outside SCP) & another inside String Constant Pool (SCP).
String str1 = new String(“James”);
As stated above, the same string object is created inside SCP as well as in heap memory (outside SCP).
But, String reference str1, always refers only to the object present in heap memory (outside SCP).
1) When we try to create a new String object with some string, if String Constant Pool (SCP) already contains the String object with the same string, then new object with the same string is not created in SCP. It is applicable for both, whether String object is created using string literal or new operator. 2) Using new operator when we try to create a new String object with some string, although Heap Memory (outside SCP) already contains the String object with the same string, the new object with the same string is created again in Heap Memory.
To understand it properly, let’s take examples of creating String objects using a string literal as well as new operator.