Java
Programming
String Comparison
Operators
Code Optimization

String.equals versus ==

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

In Java, comparing strings for equality is a fundamental concept that often leads to confusion among developers, particularly in distinguishing between using String.equals() and the == operator. Understanding the differences between these two methods is crucial for preventing bugs and ensuring that your program behaves as expected.

Understanding == Operator

The == operator, when used with objects in Java, checks for reference equality. Reference equality means that the == operator checks whether both references (the variables) point to the exact same object in memory. Therefore, when you use == to compare strings or any objects, it checks if both references are to the same instance.

For example:

java
1String a = "Hello";
2String b = "Hello";
3String c = new String("Hello");
4
5System.out.println(a == b); // true
6System.out.println(a == c); // false

In this case, a == b returns true because both a and b refer to the same instance of the string literal "Hello" that is interned in Java's string pool. However, a == c returns false because c is created as a new String object and hence points to a different location in memory.

Understanding String.equals()

The equals() method, on the other hand, is intended for checking logical equality of the content within the strings, regardless of whether the references point to the same object. This method compares the characters within the strings.

Following up on the previous example:

java
1String a = "Hello";
2String b = "Hello";
3String c = new String("Hello");
4
5System.out.println(a.equals(b)); // true
6System.out.println(a.equals(c)); // true

Both a.equals(b) and a.equals(c) return true because the actual contents of the strings are identical, even though b and c are different objects in memory.

Key Differences and Situations for Use

  • Memory Location vs. Content: As discussed, == checks if two string variables point to the exact same string object, whereas equals() compares the content within the strings.
  • String Interning: Java automatically interns string literals. Therefore, == comparison might unpredictably return true for two different string literals because they might refer to the same interned instance. However, this does not apply if new strings are created with the new keyword. Always use equals() for content comparison to avoid this confusion.
  • Null Safety: The equals() method can throw a NullPointerException if the string on which it is called is null. It's safer to perform a null check before calling equals(), or use Objects.equals(String a, String b) which is null-safe.

Practical Implications

In real-world applications, especially those involving collection classes like HashMap or List, using the wrong string comparison method might lead to very subtle and hard-to-track logic errors. Equality checks in these cases should almost always use .equals(), because the contents of the strings being compared determine logical equivalence, not their references.

Summary Table

AspectUsing ==Using .equals()
Comparison TypeReference EqualityContent Equality
Null SafetySafe (no exception thrown)Potentially unsafe
Correct Use CaseChecking if two references are identicalChecking if two strings are identical in content
String Pool ImpactAffected (may return false positive)Not affected

In conclusion, understanding the difference between == and .equals() in Java string comparison is vital. Use == when you need to check if two references are exactly the same. For comparing the contents of strings, always use equals(), keeping in mind the potential for NullPointerException and ensuring to do appropriate null checks or using null-safe equivalents like Objects.equals().


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.