String Literal Interning by Default
You'll learn: How Java automatically places all string literals into the intern pool at compile time, saving memory without any effort on your part.
The Automatic Optimization
When you write a string literal directly in your Java code—like "hello" or "Java"—the compiler automatically adds it to the string intern pool. This happens during compilation, before your program even runs. You don't need to call any special method or take any action; it's built into how Java handles string literals.
This means if you write "hello" in ten different places throughout your code, the JVM creates only one String object in the intern pool. All ten references point to that same object in memory.
How It Works
String a = "apple";
String b = "apple";
String c = "apple";
// All three variables point to the SAME object in the intern pool
System.out.println(a == b); // true (same object reference)
System.out.println(b == c); // true (same object reference)
Each "apple" literal references the identical interned String object. This automatic behavior saves memory and enables fast reference equality checks.
Think of It Like a Dictionary
Imagine the intern pool as a dictionary at compile time. When the compiler sees "apple", it checks: "Do I already have 'apple' in my dictionary?" If yes, it uses the existing entry. If no, it adds it once. Either way, every "apple" literal in your code maps to the same dictionary entry.
This default interning applies only to literals—strings created with new String(...) or through concatenation at runtime are not automatically interned unless you explicitly call .intern() on them.
Key Takeaway:
All string literals in Java source code are automatically interned at compile time, ensuring identical literals share a single object in memory without any programmer intervention.