Sub topic 15
String Pool, Interning, and Identity
Java can have two String objects that contain the same text. They have equal contents, but they may not be the same object.
This chapter explains how Java shares some string objects through the string pool, and why you should normally compare strings with equals, not ==.
You should already be comfortable creating strings and calling methods.
Contents and identity
An object is a value stored in memory. A String object holds text.
A reference is a value that points to an object. A variable of type String holds a reference to a string object.
Two references can point to:
- The same string object.
- Two separate string objects with the same text.
- Two string objects with different text.
Identity asks whether two references point to the same object. Content equality asks whether two strings hold the same text.
For string references, == checks identity. The equals method checks contents.
What is the string pool?
The string pool is a place where Java keeps shared string objects. It lets code use one shared object for a particular string value rather than always making a separate object.
A string literal is text written in double quotes in Java code, such as "Java". Java uses a pooled string for a literal. If two literals have the same text, they refer to the same pooled string object.
Strings are immutable, which means their contents cannot change after they are created. This makes sharing them safe: code using one reference cannot change the text seen through another reference.
Not every string is in the pool. A program can also create separate string objects with the same contents.
Interning a string
Interning means asking Java for the pooled string with the same contents as a given string. The intern() method does this:
- If the pool already contains an equal string,
intern()returns a reference to that pooled string. - Otherwise, Java adds the string to the pool and returns a reference to it.
The returned reference is important. Calling intern() does not change the variable you called it on. If you want to use the pooled reference, save the result.
The pooled string for a value is sometimes called its canonical string. Here, canonical means the shared string chosen by the pool for those contents.
Worked example
Save this program as PoolDemo.java:
public class PoolDemo {
public static void main(String[] args) {
String literal = "Java";
String sameLiteral = "Java";
String copy = new String("Java");
String canonical = copy.intern();
System.out.println("literal == sameLiteral: "
+ (literal == sameLiteral));
System.out.println("literal == copy: "
+ (literal == copy));
System.out.println("literal.equals(copy): "
+ literal.equals(copy));
System.out.println("literal == canonical: "
+ (literal == canonical));
System.out.println("copy == canonical: "
+ (copy == canonical));
}
}Compile it with javac PoolDemo.java, then run it with java PoolDemo.
| Output line | Result | Why |
|---|---|---|
| `literal == sameLiteral` | `true` | Both literals refer to the same pooled object. |
| `literal == copy` | `false` | `new String("Java")` creates a separate object. |
| `literal.equals(copy)` | `true` | Both objects contain the same text. |
| `literal == canonical` | `true` | `intern()` returned the pooled string. |
| `copy == canonical` | `false` | Interning did not change what `copy` refers to. |
The example uses new String(...) to make the identity difference clear. You usually do not need to create strings this way.
The two objects contain equal text, but they are still separate objects. The pool does not turn every equal string into the same object.
Literals and text built at run time
A compiler translates Java source code into a form Java can run. A constant expression is an expression whose value the compiler can determine from its parts.
For example, "Ja" + "va" is a constant expression. Java treats its result as a pooled string. But joining variables that are not constants happens at run time, while the program is running, and creates a new string object.
Try this program as ConstantDemo.java:
public class ConstantDemo {
public static void main(String[] args) {
String literal = "Java";
String constantResult = "Ja" + "va";
String first = "Ja";
String second = "va";
String runtimeResult = first + second;
System.out.println("literal == constantResult: "
+ (literal == constantResult));
System.out.println("literal == runtimeResult: "
+ (literal == runtimeResult));
System.out.println("literal == runtimeResult.intern(): "
+ (literal == runtimeResult.intern()));
System.out.println("literal.equals(runtimeResult): "
+ literal.equals(runtimeResult));
}
}Compile it with javac ConstantDemo.java and run it with java ConstantDemo.
| Comparison | Result |
|---|---|
| `literal == constantResult` | `true` |
| `literal == runtimeResult` | `false` |
| `literal == runtimeResult.intern()` | `true` |
| `literal.equals(runtimeResult)` | `true` |
The first comparison is true because the compiler can determine the joined text. The second is false because runtimeResult is a separate object. Its contents are still equal to those of literal.
A variable can be part of a constant expression if it meets Java's rules for a constant variable. For example, final String first = "Ja"; declares a constant variable. However, final alone does not make every value a compile-time constant: a value read from a user at run time is not known to the compiler.
Choose the right comparison
Use equals when your question is “Do these strings contain the same text?” That is the usual question in application code.
Use == when your question is specifically “Are these references pointing to the same object?” That question is useful for learning about the pool, but it is rarely what text comparison needs.
For example, if name contains text read from a user, compare it with "Ada".equals(name). Do not depend on name == "Ada": the user’s text may be in a separate string object.
A reference can also be null, meaning it points to no object. Calling a method on null causes an error. Writing "Ada".equals(name) is safe when name is null; it returns false.
If either value might be null, java.util.Objects.equals(first, second) is another option. It returns true if both are null, and otherwise compares their contents when they are strings.
When should you intern?
Most programs do not need to call intern(). Java already pools string literals, and equals works for both pooled and unpooled strings.
Interning may be useful when a program handles many repeated values and needs a shared reference for each value. But it has costs: Java must check the pool, and adding many different strings can use memory. Do not intern every piece of user input by default.
If memory use is a concern, measure your program before and after a change. Do not rely on the pool to keep an interned string available forever when nothing else refers to it.
Practice
Exercise
String a = "cat"; String b = new String("cat"); String c = b.intern(); What are the results of a == b, a.equals(b), and a == c?
Show answer
They are false, true, and true. b refers to a separate object with the same contents. c refers to the pooled object used by the literal.
Exercise
A user enters a name. Why should you use "Ada".equals(name) rather than name == "Ada"?
Show answer
equals checks the text, even if the two references point to separate objects. Calling it on the literal also returns false, rather than causing an error, if name is null.