Library contents

Java 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.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(new String("A").intern() == "A".intern());
    }
}
Output
true

Syntax

Java 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.java

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

From the programSystem.out.println(status.intern() == "paid")
Resulttrue
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        String status = new String("paid");
        System.out.println(status.intern() == "paid");
    }
}
Output
true

The string literal already represents the pooled value.

Advertisements

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.

Resulttrue
Main.java
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());
    }
}
Output
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?

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