
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
String Literal Storage in String Constant Pool in Java
In Java, the string literals (or, string objects) are stored in a separate memory area called string constant pool to improve the performance of string operations and optimize the memory while using them. Let's understand how.
Creating String Objects in Java
There are two ways to create a String object in Java:
- Using the new operator
- Using String literal
Example
The example given below shows how to create a string object:
public class Example { public static void main(String[] args) { // Using new operator String str1 = new String("Tutorials Point"); // Using string literal String str2 = "Tutorials Point"; System.out.println("String using new operator: " + str1); System.out.println("String using string literal: " + str2); } }
On running the above program, it will print the string literals as shown below:
String using new operator: Tutorials Point String using string literal: Tutorials Point
Use of String Constant Pool
Whenever we call new String() in Java, it creates a new object in the heap memory, whereas String literals are stored in the String Constant Pool. Unlike other objects, which are always created in the heap, the JVM handles String literals in a special way.
For String objects, the JVM uses the String Constant Pool to reduce memory usage by avoiding duplicate String objects. The String Constant Pool is a memory area inside the heap where Java stores literal String values.
One important characteristic of the String Constant Pool is that it does not create a new String object if an equivalent String already exists in the pool.
Example
The following Java program shows the use of string constant pool:
public class SCPDemo { public static void main (String args[]) { String s1 = "Tutorials Point"; String s2 = "Tutorials Point"; System.out.println("s1 and s2 are string literals:"); System.out.println(s1 == s2); String s3 = new String("Tutorials Point"); String s4 = new String("Tutorials Point"); System.out.println("s3 and s4 with new operator:"); System.out.println(s3 == s4); } }
The s1 and s2 are String literals. When the JVM encounters the literal "Tutorials Point", it checks the String Constant Pool. Since the literal already exists after the first assignment to s1, s2 simply points to the same reference.
Hence, s1 == s2 returns true. The s3 and s4 are created using the new keyword. It creates two new String objects in the heap memory, even though the content is the same. As a result, s3 == s4 returns false.
s1 and s2 are string literals: true s3 and s4 with new operator: false