String Pool & ImmutabilityAdvanced
1Question 1 of 1
javaHow does the String Pool and String Immutability work in Java?
Explanation & Concept
Strings in Java are immutable: once created, their internal byte array cannot be changed.
To conserve memory, the JVM maintains the **String Pool** inside the Heap. When string literals are created (`"abc"`), the JVM reuses existing instances from the pool. Calling `new String("abc")` bypasses the pool and allocates a new heap object.
Code Example
java
public class StringPoolDemo {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "hello"; // Reuses instance from String Pool
String s3 = new String("hello"); // New object on Heap
System.out.println(s1 == s2); // true (Same memory reference!)
System.out.println(s1 == s3); // false (Different objects)
System.out.println(s1.equals(s3)); // true (Same content value)
}
}How It Works & Key Takeaways
String immutability makes Strings inherently thread-safe and allows caching their `hashCode()` for instant `HashMap` lookups.
Mock Test · 1 Questions · Optional
Ready for Reflection API?
Take a quick test to evaluate yourself, or move straight to the next module.
Advanced1 questions