How does String interning work, and when would you actually use intern() in production?
⚡ Short Answer
intern() returns the pooled canonical instance for an equal String, so duplicates share one object. Useful when ingesting huge volumes of repeated Strings (e.g. country codes) to cut heap — but misuse can bloat the pool and hurt GC.
☕Coffee Chat Question
Concept Made Simple
“How does String interning work, and when would you actually use intern() in production?”
🧠Mind Map Answer
Remember It Faster
The String pool is a JVM-managed set of canonical Strings. intern() says *'give me the shared copy of this value'*. Two interned equal Strings are ==.
⌨️Hands-on Keyboard
Learn by Doing
String a = new String("IN").intern();
String b = "IN";
System.out.println(a == b); // true — both pooledtrue
🔥What If?
Think Beyond the Expected
You intern() every value from a 50M-row feed and GC time spikes — why?
Interning unique/high-cardinality values fills the pool, which lives on the heap and is GC-scanned. Only intern low-cardinality, frequently-repeated values; otherwise you trade duplicate Strings for a giant pool.
😂Real World
A market-data pipeline interned a small set of exchange/currency codes appearing billions of times, cutting heap noticeably — but the team explicitly avoided interning order IDs (all unique).
🎯Interviewer's Expectation
Keywords they're listening for:
⚠️Common Mistakes
- ✗Interning high-cardinality values
- ✗Assuming intern() is free
- ✗Using intern() for locking (anti-pattern)
✅Best Practices
- ✓Intern only low-cardinality, high-frequency Strings
- ✓Prefer G1 string deduplication over manual intern() for general dedup
- ✓Measure heap before/after with a profiler
🔁Follow-up Questions
- 1Where did the pool move in Java 7 and why?
- 2What is JVM string deduplication (-XX:+UseStringDeduplication) with G1?
- 3How does this relate to flyweight pattern?
🧩Related Technologies
Continue Learning with AI
Take this question deeper with your favourite AI assistant. Pick a depth, copy the prompt, or open it directly — AI is your learning companion, not a shortcut.
Plain-language foundations
I'm preparing for a software engineering interview and want to understand this from scratch, as a beginner. Topic: Strings (Core Java) Interview question: "How does String interning work, and when would you actually use intern() in production?" Please: 1. Explain the core idea in simple, plain language, using an everyday analogy. 2. Define any technical terms you use. 3. Walk through one small, concrete example. 4. Finish with a single sentence I can easily remember. Keep the tone friendly and assume I'm new to this topic.
Was this answer helpful?
⭐ Featured Products
Support our platform by exploring our recommended products.
As an Amazon affiliate, purchases through these links may earn us a small commission — at no extra cost to you. It helps keep Full Stack Interview Guru free.