Library contents

Groovy String.intern

Return the canonical pooled String for the same character sequence.

A simple example

String.intern

  1. Start with Two separate strings containing A
  2. Do this Intern both
  3. Result Same canonical reference
The pool supplies one reference for strings that contain the same characters.

Syntax

Groovy 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.groovy

Canonicalize 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.

Resulttrue
Lesson.groovy
String status = new String("paid")
println status.intern().is("paid")
Output
true

Equal interned String values share one representative.

Advertisements

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.

Resulttrue
Lesson.groovy
String a = new String("BIO")
String b = new String("BIO")
println a.intern().is(b.intern())
Output
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?

GivenNC-17
Worked resultNC-17

What to watch for

Use equals for general text comparison. Interning is most relevant when a program intentionally canonicalizes repeated symbols.

Documentation for String.intern