How does String interning work, and when would you actually use intern() in production?
Reviewed by Gurusankar M.
β‘ 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.