When Strings Are NOT Interned
What you'll learn: You'll discover which string creation methods bypass the intern pool, leaving you with distinct objects in heap memory.
The Exception to the Pool
While Java automatically interns string literals, not all strings get this special treatment. Two common scenarios create strings that live outside the intern pool:
- Using the
new String()constructor - Runtime concatenation with the
+operator orconcat()method
These approaches create fresh String objects on the heap, even if identical strings already exist in the pool.
Why This Matters
String literal = "hello"; // In intern pool
String constructed = new String("hello"); // New object, NOT in pool
String concatenated = "hel" + "lo"; // Compile-time: in pool
String runtimeConcat = "hel".concat("lo"); // Runtime: NOT in pool
System.out.println(literal == constructed); // false - different objects
System.out.println(literal == concatenated); // true - both from pool
System.out.println(literal == runtimeConcat); // false - new object
The Pattern
Think of the intern pool like a VIP guest list at a venue. String literals automatically get on the list. But strings created with new String() or built at runtime buy regular tickets—they're in the venue (memory), but not on the exclusive list. You can still manually add them using intern(), but they don't get automatic entry.
When It Happens
Any operation that constructs strings dynamically—reading from files, user input, StringBuilder results, or explicit new String() calls—produces non-interned strings.
Key Takeaway: Strings created with new String() or generated at runtime through concatenation bypass the intern pool entirely, creating separate heap objects until explicitly interned with intern().