What does the intern() method of String do?
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
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: trueWhat 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.