Groovy 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
Syntax
public String intern()
Run these examples in Groovy
Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.
groovy Lesson.groovyCanonicalize a repeated status
A dispatch feed repeats a small set of status words throughout the day. Compare the canonical objects returned for identical status text before using identity to count distinct labels.
String status = new String("paid")
println status.intern().is("paid")
true
Equal interned String values share one representative.
Compare independent tag imports
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.
String a = new String("BIO")
String b = new String("BIO")
println a.intern().is(b.intern())
true
The identity comparison is meaningful here because both sides were interned.
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.