Interview Q&A / Java

IntermediateQuick answer1 min readUpdated 3 Oct 2026

What does the intern() method of String do?

SHORT ANSWER

intern() returns the pooled copy of a string. If the pool already holds an equal string it returns that one, otherwise it adds this string to the pool and returns it, so interned strings with equal text compare equal with ==.

Explain it simply

Think of the pool as a register of names at a society gate. When a visitor says "Sharma", the guard checks the register. If "Sharma" is already listed, the guard points to that line. If not, the guard writes it in and points to the new line. intern() is that lookup.

Example

java
String a = new String("java");   // heap object, not the pool one
String b = a.intern();           // pooled "java"
String c = "java";               // pooled "java"

System.out.println(a == c);      // prints: false
System.out.println(b == c);      // prints: true

What to say in the interview

"intern() gives me the canonical pooled instance for a string's content. It is useful when I have millions of repeated strings, such as city names read from a file, and want to store one copy. The cost is a pool lookup on each call, so it is a rare optimisation, not a habit. I still use equals for comparison, never == on interned strings in normal code."

Common mistakes

  • Believing intern() changes the object it is called on. It returns a different reference, and the original is untouched.
  • Calling it everywhere, which adds lookup time and gains nothing for short-lived strings.

#java#strings#string-pool

Related questions

Practise more Java questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Java quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.