What is String constant pool in Java ?

Posted in Java Strings By Raj On December 15, 2017


In Java you can create string object in two ways, you can use either string literal approach or using new keyword, the String literal is something like assigning series of characters to the variable which is in the double quotes, the examples for string literal and new operator are mentioned below

You know that the string is reference type so the JVM stores string object into the heap memory,

What happens when you create a string literal, the JVM creates an object into the string constant pool, if you create another string, first the JVM looks for string object in the string constant pool, if it exists then it will return the reference of existing string object otherwise it will create a new object and return its reference


In the below example, if you compare the string literals then it is returning true and if you compare the string literal with the string object which is created using new operator is returning false

if you want to compare a string literal with string object then you need to use either equal or use intern method