The equals() method compares whether two strings contain the same text. It returns true or false. This is the method you should use instead of == when comparing string content in Java.
01
Content Compare
Same text or not.
02
Not ==
Value vs reference.
03
Returns boolean
true or false.
04
Case Sensitive
A ≠ a by default.
05
Null Safe Arg
equals(null) → false.
06
Validation
Login, commands.
Fundamentals
Definition and Usage
In Java, equals(Object obj) is inherited from java.lang.Object and overridden by String to compare character content. When both operands are strings with identical characters, "Hello".equals("Hello") returns true.
The == operator checks object identity—whether two variables refer to the exact same object in memory. Two different String objects can hold the same text; equals() detects that match while == may not.
💡
Beginner Tip
Rule of thumb: use equals() to compare string values. Reserve == for checking whether two references are the same object (rare in everyday string code).
Foundation
📝 Syntax
The equals() method is declared in the Object class and overridden in String:
java
public boolean equals(Object anotherObject)
Parameters
anotherObject — the object to compare with. May be null or any type; returns true only when it is a String with matching content.
Return Value
Returns true if both strings contain the same characters in the same order; otherwise false.
Exceptions
Does not throw an exception when the argument is null—it returns false. Calling equals on a null string reference (e.g. null.equals("x")) throws NullPointerException.
Cheat Sheet
⚡ Quick Reference
Expression
Result
"Java".equals("Java")
true
"Java".equals("java")
false (case-sensitive)
"Hi".equals(null)
false
new String("A") == new String("A")
false (different objects)
new String("A").equals(new String("A"))
true (same content)
Compare text
str1.equals(str2)
Same content?
Null-safe
"expected".equals(input)
input may be null
Ignore case
s1.equalsIgnoreCase(s2)
Case-insensitive
Never use
str1 == str2
For content compare
Hands-On
Examples Gallery
These programs run in Java 8+. They show matching strings, unequal text, the critical == vs equals() difference, case sensitivity, and null-safe comparison.
📚 Getting Started
Compare two strings that look identical.
Example 1 — Equal String Content
Both variables hold "Hello, World!", so equals() returns true.
java
public class StringEqualsExample {
public static void main(String[] args) {
String str1 = "Hello, World!";
String str2 = "Hello, World!";
boolean same = str1.equals(str2);
System.out.println("Equal content? " + same);
}
}
📤 Output:
Equal content? true
How It Works
Java compares each character in order. Every character matches, so the method returns true.
Example 2 — Different String Content
When the text differs, equals() returns false.
java
public class NotEqualDemo {
public static void main(String[] args) {
String greeting = "Hello, World!";
String other = "Hello, Java!";
System.out.println("Equals Java? " + greeting.equals(other));
}
}
📤 Output:
Equals Java? false
How It Works
The strings match until World vs Java. The first mismatch makes the result false.
📈 Practical Patterns
Reference vs content, case rules, and safe null handling.
Example 3 — equals() vs == Operator
Two new String("Java") objects have the same text but are different objects in memory.
java
public class EqualsVsReference {
public static void main(String[] args) {
String a = new String("Java");
String b = new String("Java");
System.out.println("a == b: " + (a == b));
System.out.println("a.equals(b): " + a.equals(b));
}
}
📤 Output:
a == b: false
a.equals(b): true
How It Works
== compares memory addresses. equals() compares characters. This is one of the most common Java interview topics—and a frequent source of bugs when confused.
Example 4 — Case-Sensitive Comparison
Letter case matters. Java and java are not equal with equals().
java
public class CaseSensitiveEquals {
public static void main(String[] args) {
String lang = "Java";
System.out.println("Equals 'Java'? " + lang.equals("Java"));
System.out.println("Equals 'java'? " + lang.equals("java"));
}
}
📤 Output:
Equals 'Java'? true
Equals 'java'? false
How It Works
The capital J differs from lowercase j. Use equalsIgnoreCase() when case should not matter.
Example 5 — Null-Safe Comparison
Put the known literal on the left so a null variable does not cause a crash.
java
public class NullSafeEquals {
public static void main(String[] args) {
String userInput = null;
// Safe: literal on the left
System.out.println("Yoda? " + "Yoda".equals(userInput));
// equals(null) on a non-null receiver returns false
System.out.println("Null arg? " + "Java".equals(null));
}
}
📤 Output:
Yoda? false
Null arg? false
How It Works
"Yoda".equals(userInput) safely returns false when userInput is null. Calling userInput.equals("Yoda") would throw NullPointerException.
Applications
🚀 Common Use Cases
Input validation — check whether the user typed an expected command or answer.
Authentication — compare a entered password string with a stored value (never plain text in production; this illustrates the API).
Configuration — branch logic when a setting equals "true" or "production".
Menu systems — match user selection strings to menu options.
Collections logic — filter or search lists when item text must match exactly.
🧠 How equals() Works
1
You pass an object
The host String compares itself to the argument.
Input
2
Type and null check
null or non-String types return false immediately.
Validate
3
Character-by-character
If lengths match, each character is compared in order.
Compare
=
✅
boolean answer
true when every character matches; false otherwise.
Important
📝 Notes
equals() compares content, not object identity—use it instead of == for strings.
It is case-sensitive. Use equalsIgnoreCase() when case should not matter.
String literals with the same text may share a pool reference, so == can appear to work—do not rely on that.
For comparing a String with a StringBuilder, use contentEquals(), not equals().
Performance
⚡ Optimization
equals() is highly optimized in the JDK and is the correct choice for content comparison. Compare against a literal first when possible ("OK".equals(status)) to avoid null checks. In hot loops, avoid repeated case conversions—normalize once or use equalsIgnoreCase() directly when appropriate.
Wrap Up
Conclusion
The equals() method is the standard way to compare string content in Java. It keeps your code correct, readable, and safe from the common == pitfall.
Remember case sensitivity, null-safe calling patterns, and when to reach for equalsIgnoreCase() or contentEquals(). With those rules in mind, string comparisons become reliable in real programs.
Write "expected".equals(variable) when variable may be null
Use equalsIgnoreCase() when case should not matter
Use Objects.equals(a, b) when both references may be null
Prefer equals() over manual character-by-character loops
❌ Don’t
Use == to compare string text (except intentional identity checks)
Call equals() on a reference that might be null without guarding
Assume equals() ignores case
Compare a String to a StringBuilder with equals()
Rely on string interning so == “usually works”
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about equals()
Use these points whenever you compare strings in Java.
5
Core concepts
⚖️01
Content Compare
Same text or not.
Purpose
≠02
Not ==
Value vs reference.
Critical
🔑03
Case Sensitive
Use ignoreCase if needed.
Edge case
🛡️04
Null Safe
Literal on the left.
Pattern
✅05
Returns boolean
true or false.
Return
❓ Frequently Asked Questions
equals(Object obj) compares the character content of the calling String with another object. When the argument is also a String with the same characters in the same order, it returns true; otherwise false.
== checks whether two references point to the same object in memory. equals() checks whether two Strings contain the same text. Always use equals() to compare string content, not ==.
Yes. "Java".equals("java") returns false. Use equalsIgnoreCase() when letter case should not matter.
It returns false without throwing an exception. The String method safely handles a null argument.
Prefer "Java".equals(str) when str might be null. If str is null, str.equals("Java") throws NullPointerException, but "Java".equals(str) simply returns false.
Use it for password checks, command parsing, configuration values, map keys comparison logic, and anywhere you need to know if two strings represent the same text.