The String Pool in Java is a special memory area inside the Heap where string literals are stored. It improves memory efficiency by reusing immutable string objects instead of creating duplicate instances.
new keyword are stored outside the poolintern() method moves strings to the poolWhen a string literal is created, JVM checks the String Pool first. If the value already exists, it reuses the reference. Otherwise, a new string is added to the pool.
// String literals are stored in the String Pool
String s1 = "Java";
String s2 = "Java";
// Comparing references
System.out.println(s1 == s2);
// String created using new keyword is outside the pool
String s1 = "Hello";
String s2 = new String("Hello");
// Reference comparison
System.out.println(s1 == s2);
// intern() moves the string to the String Pool
String s1 = new String("World");
String s2 = s1.intern();
// Now both references point to pool memory
System.out.println(s1 == s2);
Define two strings and see how Java compares them.
new String()equals() for value comparisonintern() cautiously in large applicationsnew and compare referencesintern() with user input strings