Java String Equality: ==, equals, the String Pool and intern (OCP 21)
When == is true for Java strings and when it isn't: the string pool, compile-time constants and final variables, runtime concatenation, new String, intern(), equals versus == for String, StringBuilder, arrays and records, and why real code should always use equals.
kvi5hnuCode Sprout team member7 min readOn this page
== on references asks whether two variables point to the same object. equals asks whether two objects are equivalent by whatever rule the class defines. For most classes the difference is easy to see, but String blurs it, because the JVM quietly reuses string objects through the string pool. Two strings created in different places can be the same object or two separate ones, depending on details the exam loves to test. This article shows how to predict the result of == on strings, and why you should never rely on it in real code.
== versus equals
var left = new StringBuilder();
var right = new StringBuilder();
var same = left.append("x");
System.out.println(left == right); // false: two separate objects
System.out.println(left == same); // true: append returned the same object
equals is defined in Object, where it does exactly what == does. Classes can override it to compare contents:
| Type | equals compares | Notes |
|---|---|---|
String | Characters, case-sensitive | equalsIgnoreCase ignores case |
StringBuilder | References (not overridden) | Compare toString() values instead |
| Arrays | References (not overridden) | Use Arrays.equals (article 21) |
| Records | Every component | Generated automatically (Chapter 7) |
Wrappers (Integer…) | Value and type | Integer.valueOf(1).equals(1L) is false |
If the compiler can tell that two references can never point to the same object, because their types are unrelated, == doesn't compile. "a" == new StringBuilder("a") fails with "incomparable types".
The string pool
Strings are everywhere, and many have the same value: class names, keys, messages. The JVM keeps a string pool (also called the intern pool) of unique String objects. Because strings are immutable, they can safely be shared.
What goes into the pool automatically:
- every string literal in your code, including text blocks;
- every compile-time constant expression of type
String.
What doesn't:
- strings computed at run time: concatenation that involves a non-constant, the results of method calls,
StringBuilder.toString(), input data; - anything created with
new String(…), which always makes a separate object.

Compile-time constants
The compiler evaluates a constant expression and stores one literal in the class file. These are all constant expressions:
String pooled = "penguin";
pooled == "penguin"; // true: the same literal
pooled == "pen" + "guin"; // true: folded into "penguin" by the compiler
static final String PREFIX = "pen";
pooled == PREFIX + "guin"; // true: PREFIX is a constant variable
final String localFinal = "pen";
pooled == localFinal + "guin"; // true: a final local initialized with a constant
pooled == """
penguin"""; // true: text blocks are literals too
A constant variable is a final variable of primitive or String type, initialized with a constant expression. Remove final, or initialize it from a method call, and it's no longer a constant:
String notFinal = "pen";
pooled == notFinal + "guin"; // false: computed at run time
final String fromMethod = suffix(); // final but not a constant
pooled == "pen" + fromMethod; // false
String built = "pen";
built += "guin";
pooled == built; // false: += runs at run time
pooled == new String("penguin"); // false: new always creates an object
pooled == " penguin ".strip(); // false: a computed result
The same constant rules apply to primitives: with final int one = 1;, "rat" + one is the constant "rat1", and ("rat" + one) == "rat1" is true.
intern()
public String intern()
intern() returns the pooled String with the same characters, adding this string to the pool first if no such string is there yet. After interning, == works for equal values:
pooled == built.intern(); // true
pooled == new String("penguin").intern(); // true
A useful way to solve exam questions: mark each string as pooled (a literal, a constant expression, or an intern() result) or runtime (anything else). Two pooled strings with equal values are ==. A runtime object is == only to itself.
Use equals
The pool is an optimization, not a contract you can build on. Whether two strings are == depends on how each one was produced, which can change when someone refactors a line. Always compare strings with equals (or equalsIgnoreCase, or compareTo for ordering), and use Objects.equals(a, b) when either side might be null:
"Penguin".equals(pooled); // false: case matters
built.equals(pooled); // true
Objects.equals(null, null); // true, no NullPointerException
"x".equals(null); // false
Writing the literal first, as in "yes".equals(answer), also avoids a NullPointerException when answer is null.
intern() in application code is rarely worth it. The JVM can instead deduplicate the character arrays of identical strings during garbage collection, with no code changes: enable it with -XX:+UseStringDeduplication (G1 has supported it since Java 8u20, and all collectors since Java 18). It shares the internal arrays, not the String objects, so it never changes the result of ==.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- The string pool lives on the heap (since Java 7), so pooled strings can be garbage collected. The G1 option
-XX:+UseStringDeduplicationshares the character arrays of equal strings. It doesn't change what==returns and isn't on the exam.
Exam traps from this article
A complete example
import java.util.Arrays;
import java.util.Objects;
public class Solution {
static final String PREFIX = "pen"; // a constant: folded at compile time
static String suffix() { return "guin"; }
record Badge(String name) {} // records get a value-based equals
static void check(String label, boolean result) {
System.out.printf("%-34s %s%n", label, result);
}
public static void main(String[] args) {
String pooled = "penguin";
System.out.println("-- compile-time constants share the pooled object --");
check("\"penguin\" == \"penguin\"", pooled == "penguin");
check("\"pen\" + \"guin\"", pooled == "pen" + "guin");
check("PREFIX + \"guin\" (static final)", pooled == PREFIX + "guin");
final String localFinal = "pen";
check("localFinal + \"guin\"", pooled == localFinal + "guin");
check("text block", pooled == """
penguin""");
System.out.println("-- values computed at run time are new objects --");
String notFinal = "pen";
check("notFinal + \"guin\"", pooled == notFinal + "guin");
check("\"pen\" + suffix()", pooled == "pen" + suffix());
String built = "pen";
built += "guin";
check("+= result", pooled == built);
check("new String(\"penguin\")", pooled == new String("penguin"));
check("StringBuilder.toString()", pooled == new StringBuilder("penguin").toString());
check("\" penguin \".strip()", pooled == " penguin ".strip());
System.out.println("-- intern() returns the pooled copy --");
check("built.intern()", pooled == built.intern());
check("new String(...).intern()", pooled == new String("penguin").intern());
System.out.println("-- equals compares the characters --");
check("built.equals(pooled)", built.equals(pooled));
check("new String(...).equals(pooled)", new String("penguin").equals(pooled));
check("\"Penguin\".equals(pooled)", "Penguin".equals(pooled));
check("Objects.equals(null, null)", Objects.equals(null, null));
System.out.println("-- other types --");
var sb1 = new StringBuilder("x");
var sb2 = new StringBuilder("x");
check("StringBuilder equals", sb1.equals(sb2));
int[] n1 = {1, 2};
int[] n2 = {1, 2};
check("array equals", n1.equals(n2));
check("Arrays.equals", Arrays.equals(n1, n2));
check("record equals", new Badge("Pip").equals(new Badge("Pip")));
check("record ==", new Badge("Pip") == new Badge("Pip"));
}
}
Output:
-- compile-time constants share the pooled object --
"penguin" == "penguin" true
"pen" + "guin" true
PREFIX + "guin" (static final) true
localFinal + "guin" true
text block true
-- values computed at run time are new objects --
notFinal + "guin" false
"pen" + suffix() false
+= result false
new String("penguin") false
StringBuilder.toString() false
" penguin ".strip() false
-- intern() returns the pooled copy --
built.intern() true
new String(...).intern() true
-- equals compares the characters --
built.equals(pooled) true
new String(...).equals(pooled) true
"Penguin".equals(pooled) false
Objects.equals(null, null) true
-- other types --
StringBuilder equals false
array equals false
Arrays.equals true
record equals true
record == false
Points to notice:
- Every line in the first group is a constant expression or a literal, so the compiler stores the single pooled
"penguin". notFinaland"pen" + suffix()differ from the constant case only because the compiler can't know their values in advance.intern()maps any equal string back to the pooled object.equalsgives the meaningful answer in every case. The==results are only interesting for the exam.- Records compare by component values with
equals, but twonewrecords are still different objects for==.
Common questions
Is the string pool part of the heap? Yes. Since Java 7, the pool lives in the regular heap (before that, it was in PermGen), so pooled strings that are no longer referenced can be garbage collected.
Does new String("x") create one object or two?
The literal "x" is a pooled object that already exists once the class is loaded. new creates one more object every time the line runs. On the exam, "how many objects" questions usually count only the objects created by new or at run time.
Why does == sometimes "work" for strings in my program?
Because both values happened to be literals or constants, so they're the same pooled object. Read the value from user input or a file, and the same comparison fails. That's exactly why == is a bug.
Can I use == for enums?
Yes. Each enum constant is a single object, so == and equals give the same result, and == is even null-safe. That makes enums the exception (Chapter 7).
Summary
==compares references.equalscompares whatever the class defines: characters forString, references forStringBuilderand arrays, components for records.- String literals, text blocks and compile-time constant expressions (including
finalconstant variables) share one pooled object. - Strings computed at run time and strings created with
new Stringare separate objects. intern()returns the pooled copy, so interned equal strings are==.- Compare strings with
equals,equalsIgnoreCaseorObjects.equals, never with==.
Practice quiz
Test yourself with the string equality and pool quiz: 10 exam-style questions with explanations.
Previous: Java StringBuilder: Mutability, Chaining and Methods (OCP 21)
Related reading
- Java StringBuilder: Mutability, Chaining and Methods (OCP 21)
- Java String Methods: Indexing, Searching, Comparing and Transforming Text (OCP 21)
- Java Strings: Creation, Concatenation and Immutability (OCP 21)
- Java break, continue, Labels, return and Unreachable Code (OCP 21)
- Java while, do/while, for and for-each Loops (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.