String Intern Canonical Pool

String literals share one pooled instance, a new copy is equal but not identical, and intern() returns the canonical pooled instance for the same content.

JavaData Integrity

Code

snippet
public class InternPool {

    public static void main(String[] args) {
        String a = "alpha";
        String b = "alpha";
        // 字面量本身就在字符串常量池:相同字面量是同一对象
        System.out.println("literals identical: " + (a == b));

        // new 出来的副本与池内对象相等但不相同
        String copy = new String("alpha");
        System.out.println("equal: " + a.equals(copy) + " identical: " + (a == copy));

        // intern() 返回池内的规范实例:副本 intern 后指向同一个对象
        System.out.println("interned identical: " + (a == copy.intern()));

        // 运行时拼接的字符串不在常量池,intern 后收敛到同一规范实例
        String prefix = "al";
        String built = prefix + "pha";
        System.out.println("built identical: " + (built == a));
        System.out.println("built interned: " + (built.intern() == a));
    }
}

What the code does

String Intern Canonical Pool keeps everything in the class InternPool and the function main.

Caveats

  • No lockfile entry, no version pinning — the file needs nothing beyond the runtime.

Applying it

The signature you will call most reads public static void main(String[] args)

The demo output is labeled (literals identical:, equal:, interned identical:), so the output doubles as a step-by-step trace of what the file did.

Statements that matter most here

String copy = new String("alpha");
String built = prefix + "pha";
String prefix = "al";

Interactive Tools for This Topic

FAQ

What does String Intern Canonical Pool print when run?
Run it as a complete program — the output lines carry labels such as `literals identical:`, `equal:`, `interned identical:`.