Java String equals() Method

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Methods

What You’ll Learn

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.

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).

📝 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.

⚡ Quick Reference

ExpressionResult
"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

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);
    }
}

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));
    }
}

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));
    }
}

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"));
    }
}

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));
    }
}

How It Works

"Yoda".equals(userInput) safely returns false when userInput is null. Calling userInput.equals("Yoda") would throw NullPointerException.

🚀 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.

📝 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.equals(null) returns false; null.equals(...) throws NullPointerException.
  • 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().

⚡ 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.

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.

💡 Best Practices

✅ Do

  • Use equals() to compare string content
  • 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”

Key Takeaways

Knowledge Unlocked

Five things to remember about equals()

Use these points whenever you compare strings in Java.

5
Core concepts
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.

Compare Strings the Right Way

Next up: compare strings without worrying about capitalization using equalsIgnoreCase().

Next: equalsIgnoreCase() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful