← Back to Chapters

Java String Pool Memory

? Java String Pool Memory

? Quick Overview

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.

? Key Concepts

  • String literals are stored in the String Pool
  • Identical literals point to the same memory reference
  • Strings created using new keyword are stored outside the pool
  • Strings are immutable
  • The intern() method moves strings to the pool

? Syntax / Theory

When 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.

? Code Example(s)

? View Code Example
// String literals are stored in the String Pool
String s1 = "Java";
String s2 = "Java";

// Comparing references
System.out.println(s1 == s2);
? View Code Example
// String created using new keyword is outside the pool
String s1 = "Hello";
String s2 = new String("Hello");

// Reference comparison
System.out.println(s1 == s2);
? View Code Example
// 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);

? Live Output / Explanation

  • true → Same literal reused from pool
  • false → One object in heap, one in pool
  • false → s1 heap object vs s2 pool object

? Interactive Lab: Memory Simulator

Define two strings and see how Java compares them.

String s1

 

String s2

 
s1.equals(s2) ?
s1 == s2 ?

 

✅ Tips & Best Practices

  • Prefer string literals for memory efficiency
  • Avoid unnecessary use of new String()
  • Use equals() for value comparison
  • Use intern() cautiously in large applications

? Try It Yourself

  • Create two strings using new and compare references
  • Test intern() with user input strings
  • Compare memory behavior using literals vs objects