Understanding the String Pool in Java
How Java Optimizes Memory and Performance Using String Interning
A string pool in Java is a special memory area in the heap where string literals are stored to optimize memory usage and improve performance through string interning.
Let’s try to understand this with the examples:
Example 1: Using the new String()
String a = new String(”Outcome School”);
String b = new String(”Outcome School”);
System . out . println(a == b); // false
new String(”Outcome School”) creates a new object in heap memory, not from the pool.
Example 2: Using String Literals, Without Using the new String()
String a = “Outcome School”;
String b = “Outcome School”;
System . out . println(a == b); // true
Here, both a and b point to the same object in the String Pool. No new object is created for b.
When you create a string literal (like “Outcome School”), Java first checks if an identical string already exists in the pool. If it does, Java returns a reference to the existing string rather than creating a new one. If not, it adds the new string to the pool.
Advantages:
Reduces memory consumption by eliminating duplicate strings
Improved performance for applications with many repeated strings
Use “Outcome School” instead of new String(”Outcome School”) whenever possible, it’s more efficient due to the String Pool.
Automatic Interning: String literals are automatically interned, but strings created with new String() are not unless explicitly interned.
Manual Interning: You can manually add strings to the pool using the intern() method:
String a = new String(”Outcome School”).intern(); // Now in String Pool
String b = “Outcome School”;
System . out . println(a == b); // true
Note: Kotlin’s string pool behavior is very similar to Java’s since Kotlin compiles to JVM bytecode and uses the same underlying string handling mechanisms.
Prepare for your Android Interview: Android Interview Questions and Answers
Thanks
Amit Shekhar
Founder, Outcome School


