Fundamentals 8 min read

Understanding Java String Pool, intern() Method, and Comparison Techniques

This article explains how Java's String class encapsulates character arrays, the role of the string pool, the effects of the new operator, the intern() method, and the proper use of == versus equals() for reliable string comparison and memory optimization.

Full-Stack Internet Architecture
Full-Stack Internet Architecture
Full-Stack Internet Architecture
Understanding Java String Pool, intern() Method, and Comparison Techniques

Java's String class encapsulates a char array, providing an immutable object that represents text; developers interact with it through its public methods without needing to know its internal implementation.

The string pool stores a single instance of each distinct literal value, allowing the JVM to reuse objects and save heap memory. When a literal is encountered, the JVM checks the pool; if the value exists, the reference points to the existing object, otherwise a new one is created.

Using the new operator forces the creation of a distinct String object on the heap, even if an identical literal already resides in the pool, causing == to return false when comparing references.

The intern() method ensures that a string is placed in the pool: it returns the existing pooled instance if present, or adds the string to the pool and returns that reference, making subsequent == comparisons succeed.

The equals() method, overridden by String , compares the actual character sequences (the state) rather than object references, providing value‑based equality regardless of where the objects reside.

Commonly used String methods include trim() , substring() , toUpperCase() , toLowerCase() , and others that manipulate or query the text without altering the original immutable object.

A series of code examples (shown as images in the original article) illustrate how different combinations of literals, new , intern() , and equals() affect the result of comparisons, highlighting pitfalls such as assuming that identical content guarantees reference equality.

Strings are immutable; their state cannot change after creation.

The JVM reuses literals via the string pool to conserve memory.

Use == to compare references and equals() to compare values.

Creating a string with new always yields a new object, even if an identical value exists in the pool.

JavaMemory ManagementstringObject ComparisonequalsinternString Pool
Full-Stack Internet Architecture
Written by

Full-Stack Internet Architecture

Introducing full-stack Internet architecture technologies centered on Java

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.