- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why String literal is stored in String Constant Pool in Java?
There are two ways to create a String object in Java
By using the new operator
String str = new String("Tutorials Point");
By using String literal
String str = "Tutorials Point";
Whenever we call new String() in Java, it will create an object in the heap memory and String literals will go into String Constant Pool (SCP).
For objects, JVM used SCP which is for efficient memory management in Java. Unlike other Java objects, instead of managing String object on the heap area, they introduced the String constant pool. One of important characteristic of String constant pool is that it does not create the same String object if there is already String constant in the pool.
Example
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); } }
Output
s1 and s2 are string literals: true s3 and s4 with new operator: false
Advertisements