String in Java | String Literal, String Pool

Java String | A string is a very important topic in the world of programming languages.

In almost all programming languages such as C, C++, Java, Python, or any application, whether Java-based or Python-based, the most commonly used object is a string only.

For example, when you visit a bank to open an account, you are asked for information such as name, address like house number, street, city, state, and identification marks.

The information you provided is in the form of an ordered sequence of characters and symbols. This ordered and sequence of characters and symbols is nothing but a string in java.

So, if you are not familiar with the complete behavior of string, you are wasting your time to go to any technical interview because string is the most favorite topic for the interviewer.

Without making a command on the string, you cannot crack any technical interview. In this tutorial, we will cover the following topics.

What is String in Java?


Generally, a string is a sequence of characters. In C/C++ programming languages, it represents an array of characters, where the last character will be the null character (\0) that represents the end of the string.

But in Java, String is an object of String class that represents a string of characters. For example, “Pencil” is a string of 6 characters.

String class is used to create a string object. It is a predefined immutable class that is present in java.lang package.

But in Java, all classes are also considered as a data type. So, you can also consider a string as a data type. Immutable means it cannot be changed.

Basically, memory in Java is divided into three parts such as heap, stack, and String Pool. The string is so important in Java that it has a dedicated memory location. What string pool does it?

Whenever a string gets repeated it does not allocate the new memory for that string. It uses the same string by pointing a reference to it for saving memory.

String Class declaration in Java


The declaration of string class in java is as follows:

public final class String 
     extends Object
         implements Serializable, Comparable<String>, CharSequence

The above syntax says that string is a final class and object class is its superclass. The class implements three interfaces Serializable, Comparable, and CharSequence.

The CharSequence is an interface that is used to represent the sequence of characters. String, StringBuffer, and StringBuilder class implement it.


Note:

The String type is known as reference data type. It is not a primitive data type. In Java programming language, any class can be used as a reference type for a variable.

A variable that is declared by a reference type is called reference variable. It references an object. For example, str is a reference variable that references a string object with contents Hello World.

String str = "Hello World";

How to create String object in Java?


To handle string data in Java, we need an object of string class. Basically, there are three ways to create a String object in Java.

  1. By string literal.
  2. By new keyword.
  3. By converting character arrays into strings

Let’s understand all three ways one by one.

String literal in Java


String literal in Java is created by using double quotes.

For example:

String s = "Hello";

The string literal is always created in the string constant pool. In Java, String constant pool is a special area that is used for storing string objects.

Internally, String class uses a string constant pool (SCP). This SCP area is part of the method area (Permgen) until Java 1.6 version.

From Java 1.7 onwards, SCP area is moved in the heap memory because SCP is a fixed size in the method area but in the heap memory, SCP can be expandable.

Therefore, the string constant pool has been moved to heap area for memory utilization only.

Whenever we create a string literal in Java, JVM checks string constant pool first. If the string already exists in string constant pool, no new string object will be created in the string pool by JVM.

JVM uses the same string object by pointing a reference to it to save memory. But if string does not exist in the string pool, JVM creates a new string object and placed it in the pool.

For example:

String s1 = "Hello";
String s2 = "Hello";

Look at the below figure where we have represented string objects with contents in the memory.

Allocating memory of string objects in Java

In the above example, when JVM will execute the first statement, it will not find any string with value “Hello” in the string constant pool.

So, it will create an object in string pool and store string “Hello” in that object as shown in the above figure.

This object is referenced by the reference variable s1. In other words, if literal is not available in the pool, a new object will be created in the pool and the address of that object will be assigned to a reference variable s1.

When JVM will execute the second statement, it will first check to string constant pool to know whether string object with the same content is already available there or not. Since string with value “Hello” is already available in the string pool.

So, JVM will not create a new string object in the pool, and the address of the available object will assign to reference variable s2. That is, it will point a reference variable s2 to the old existing object as shown in the above figure.


Key points:

1. Remember that creating an object means allocating memory for storing data.
2. A string object is created for every string literal.

Creating String Object by new Keyword


The second way of creating an object to string class is by using new operator. It is just like creating an object of any class. It can be declared as follows:

String s = new String("Hello");

Whenever we will create an object of string class using the new operator, JVM will create two objects. First, it will create an object in the heap area and store string “Hello” into the object.

After storing data into memory, JVM will point a reference variable s to that object in the heap. Allocating memory for string objects is shown in the below figure.

Creating object to string class in javais by using new operator
Now JVM will create the second object as a copy for literal “Hello” in string constant pool for future purposes. There is no explicit reference variable pointing to the copy object in the pool but internally, JVM maintains the reference variable implicitly.

Remember that the object created in the SCP area is not eligible for garbage collection because implicitly, the reference variable will be maintained by JVM itself.


Key point:

1. For every string literal, one copy will be created in the SCP area.

By converting Character Arrays into String


The third way to create strings is by converting the character arrays into string. Let’s take a character type array: arr[ ] with some characters as given below:

char arr[ ] = {'j','a','v','a'};

Now create a string object by passing array name to string constructor like this:

String s = new String(arr);

Now string object ‘s’ contains string “java”. It means that all the characters of the array are copied into string.

If you do not want all the characters of the array into string then you can also mention which character you need, like this:

String s = new String(arr, 1,3);

From the above statement, total of three characters will be copied into string s. Since the original characters are j-a-v-a. So, the counting will start from 0 i.e 0th character in the array is ‘j’ and the first character is ‘a’. Starting from ‘a’, total of three characters ‘aja’ will copy into string s.

How many total objects will be created in memory for following string objects?


String s1 = new String("Scientech");
String s2 = new String("Scientech");

String s3 = "Scientech";
String s4 = "Scientech";

In the preceding code, we are creating four string objects using two new operators and 2 string literal.

How many objects will be created in the heap and SCP area?

Consider the below figure.

Allotting memory for string objects in Java

1. During the execution of first statement using new operator, JVM will create two objects, one with content in heap area and another as a copy for literal “Scientech” in the SCP area for future purposes as shown in the figure.

The reference variable s1 is pointing to the first object in the heap area.

2. When the second statement will be executed, for every new operation, JVM will create again one new object with content “Scientech” in the heap area.

But in the SCP area, no new object for literal will be created by JVM because it is already available in the SCP area. The s2 is pointing to the object in the heap area as shown in the figure.

3. During the execution of third and fourth statements, JVM will not create a new object with content “Scientech” in the SCP area because it is already available in string constant pool.

It simply points the reference variables s3 and s4 to the same object in the SCP. They are shown in the above figure.

Thus, three objects are created, two in the heap area and one in string constant pool.

This kind of question is always asked in the interview or technical tests in the different companies. So, you must prepare answers for this kind of question.


Key points:

1. Strings are objects in Java.

2. When we create a String object, we are creating a string that cannot be changed. In other words, once a String object has been created, we cannot change any characters in string. Therefore, string object is immutable in Java.

3. The number of characters in a string is called length of string. For example, the length of “Hello” is 5.

4. String class in Java has numerous methods for string manipulation.

5. String is not a primitive data type. It is a reference data type.


Hope that this tutorial has covered the basic of string in Java, string literal, and string constant pool in Java with memory concepts. I hope that you will have understood the memory concepts of string object creation.
Thanks for reading!!!Next ⇒ Immutable String in Java

⇐ PrevNext ⇒

Leave a Comment