Java Interview Questions

BY Author

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, Stringis as immutable object. That is once it is created, it cannot be changed.If we try to change a Stringobject, a new Stringobject is created, and original Stringobject 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 Stringobject is created using a string literal, the String object is stored in the String Constant Pool (SCP).When a Stringobject is created using the newoperator, it is stored in the heaparea (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, newoperator is not used.String objects can be created using string literal as shown below:

Example

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 newkeyword

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).

Example

String str1 = newString(“James”);

As stated above, the same string object is created inside SCPas well as in heap memory (outside SCP).But, String reference str1, always refers only to the object present in heap memory (outside SCP).

IMPORTANT CONDITIONS

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 newoperator.
2) Using newoperator 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 newoperator.