Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java String equals() method
Syntax and Examples



Introduction

In Java, comparing strings can be tricky. You might think using the == operator would do the job, but it actually checks if two string objects are pointing to the same memory location, not whether their content is identical. The equals() method provides a way to compare the actual character sequences of two strings.

Syntax

public boolean equals(Object anObject)

Parameters

Parameter Description
anObject The object to compare with this string. It can be any Object, but typically it will be another String.

Return Value

Returns true if the specified object is a string and its content is equal to this string's content; otherwise returns false.

Examples

Example 1: Basic String Comparison

This example demonstrates comparing two strings using the equals() method. It shows that the method correctly identifies whether two strings have the same content, even if they are different objects in memory.

public class StringEqualsExample1 {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "Hello";
        String str3 = new String("Hello");

        System.out.println(str1.equals(str2)); // Compare content
        System.out.println(str1.equals(str3)); // Compare content
        System.out.println(str1 == str2);    // Check object identity (not content)
        System.out.println(str1 == str3);    // Check object identity (not content)
    }
}
true
true
false
false

Explanation: str1 and str2 hold the same string value, so equals() returns true. Even though str3 is a new object containing "Hello", its content matches str1's, so equals() also returns true. However, because they are different objects in memory, the == operator returns false for both comparisons.

Example 2: Case Sensitivity

This example shows that equals() is case-sensitive. It compares strings with differing capitalization and demonstrates how to use equalsIgnoreCase() for case-insensitive comparison.

public class StringEqualsExample2 {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "hello";

        System.out.println(str1.equals(str2));  // Case-sensitive comparison
        System.out.println(str1.equalsIgnoreCase(str2)); // Case-insensitive comparison
    }
}
false
true

Explanation: equals() considers uppercase and lowercase characters differently. Since "Hello" and "hello" have different capitalization, equals() returns false. However, equalsIgnoreCase() ignores case differences, resulting in a return value of true.

Example 3: Comparing with Null

This example demonstrates what happens when you attempt to compare a string with null using the equals() method. It highlights the importance of null checks before calling equals() to avoid NullPointerException.

public class StringEqualsExample3 {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = null;

        if (str2 != null) {
            System.out.println(str1.equals(str2));
        } else {
            System.out.println("Cannot compare with null.");
        }
    }
}
Cannot compare with null.

Explanation: Calling equals() on a string and passing in null would result in a NullPointerException. The code includes a check to ensure that str2 isn't null before attempting the comparison, avoiding this error.

Example 4: Comparing with Non-String Objects

This example demonstrates what happens when you attempt to compare a string with an object of a different type using equals(). It emphasizes that while it is technically possible, the behavior depends on the other object's implementation of equals() or leads to incorrect results.

public class StringEqualsExample4 {
    public static void main(String[] args) {
        String str1 = "Hello";
        Integer intObj = 10;

        System.out.println(str1.equals(intObj)); // Compares with an Integer object.
    }
}
false

Explanation: While Java allows calling equals() on a String object and passing another Object as argument, the comparison result depends entirely on how the other object (Integer in this case) implements its equals() method. Generally, comparing strings with objects of different types using equals() is not recommended unless you specifically understand their behavior.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M