Java String.intern
Return the canonical pooled String for the same character sequence.
A simple example
String.intern
- Start with Two separate strings containing A
- Do this Intern both
- Result Same canonical reference
class Main {
public static void main(String[] args) throws Exception {
System.out.println(new String("A").intern() == "A".intern());
}
}
true
Syntax
public String intern()
JDK 21 method signatures (1)
public String intern()Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaCanonicalize a repeated import status
An importer creates many copies of the same short status or tag. Examine whether repeated text can share a canonical representation and when comparing those canonical objects is meaningful.
class Main {
public static void main(String[] args) throws Exception {
String status = new String("paid");
System.out.println(status.intern() == "paid");
}
}
true
The string literal already represents the pooled value.
Compare two separately assembled room codes
A reader compares two identifiers that may look similar on their labels. Use the full values under the intended case rules so a difference in one letter or digit is not lost.
class Main {
public static void main(String[] args) throws Exception {
String a = String.join("", "A", "7");
String b = new String("A7");
System.out.println(a.intern() == b.intern());
}
}
true
Both calls return the same pooled representative for the equal text.
Read a parcel sorting code
The depot scans a parcel marked NC-17. The program recovers the text of this existing string for a scanner log. What exact sequence of characters should survive?
What to watch for
Use equals for general text comparison. Interning is most relevant when a program intentionally canonicalizes repeated symbols.