Java String equals() example

In this guide, you will learn about the String equals() method in Java programming and how to use it with an example.

1. String equals() Method Overview

Definition:

The equals() method in Java's String class is utilized to compare two strings for content equality.

Syntax:

str1.equals(str2)

Parameters:

- str2: The string to be compared with str1.

Key Points:

- The equals() method returns true if and only if the argument string represents the same sequence of characters as the string object.

- Unlike the == operator, the equals() method checks for content equality and not reference equality.

- It's case-sensitive. For instance, "Hello" and "hello" are considered different strings.

- If the str2 is null, the method will return false.

2. String equals() Method Example

public class EqualsExample {
    public static void main(String[] args) {
        String sample1 = "Java";
        String sample2 = new String("Java");
        String sample3 = "JAVA";

        // Comparing two strings with identical content
        boolean areEqual1 = sample1.equals(sample2);
        System.out.println("Are sample1 and sample2 equal? " + areEqual1);

        // Comparing two strings with different cases
        boolean areEqual2 = sample1.equals(sample3);
        System.out.println("Are sample1 and sample3 equal? " + areEqual2);

        // Attempting to compare with a null string
        boolean equalsNull = sample1.equals(null);
        System.out.println("Is sample1 equal to null? " + equalsNull);
    }
}

Output:

Are sample1 and sample2 equal? true
Are sample1 and sample3 equal? false
Error: Cannot compare a string with null.

Explanation:

In the example:

1. We first compare the string "Java" with a new string object that also contains "Java". Even though they might have different references, their content is the same, resulting in true.

2. Next, we compare "Java" with "JAVA", which have different cases. Since the equals() method is case-sensitive, the output is false.

3. Lastly, we intentionally attempt to compare a string with null. The equals() method returns false when compared against null.

Related Java String Class method examples

Comments