Ch. 7 · Java

Java String Equality and Identity

Java String Equality and Identity. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readbeginnerupdated Oct 3, 2026

The equals method compares string contents; double-equals compares references. Interning can make identity comparisons appear to work accidentally.

Before you start

You should know Java classes, methods, collections and exceptions. Trace object identity separately from the contents of an object. For concurrent examples, state which thread owns or shares the data; a single successful execution is not proof that every interleaving is safe.

The practical goal is to reason through this situation: A newly constructed string can equal a literal in content but differ in reference. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.

Step-by-step walkthrough

Step 1: Distinguish identity from value

Double-equals asks whether references identify the same object.

Step 2: Compare contents deliberately

Use equals or Objects.equals for nullable string values.

Step 3: Specify text policy

Case-insensitive or locale-aware comparison is an additional requirement.

Worked scenario

A newly constructed string can equal a literal in content but differ in reference.

String a = "React";
String b = new String("React");
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
System.out.println(java.util.Objects.equals(null, b)); // false
java

Literal interning can make identity appear to work; this construction exposes the distinction.

Common mistake

Passing tests with literals does not prove double-equals compares textual values.

Verify the behavior

Test literals, separate instances, nulls and case differences under the chosen policy.

Interview exercise

Compare nullable strings.

Answer and reasoning

Use an appropriate null-safe comparison such as Objects.equals and keep case or locale policy explicit.

Continue learning

Compare the scenario with the Java interview questions and test your understanding with the Java MCQs. For terminology and implementation details, consult the reference material.

More in Java

read ✓Java · hard

Java Time Types and Zone-Aware Decisions

Java Time Types and Zone-Aware Decisions. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
read ✓Java · hard

Java Generics Wildcards and PECS

Use ? extends T for producers and ? super T for consumers, and understand why List<String> is not a List<Object>.

~2 min readread →
read ✓Java · easy

Java ArrayList Capacity and Performance

Java ArrayList Capacity and Performance. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
esc