Java String equals() and equalsIgnoreCase() Example

1. Introduction

In Java, String.equals() and String.equalsIgnoreCase() methods are used to compare two strings. The equals() method compares the strings for equality with case sensitivity, while equalsIgnoreCase() compares them for equality but ignores case differences. This tutorial will guide you through examples using both methods.

Key Points

- equals() checks for case-sensitive equality between two strings.

- equalsIgnoreCase() checks for equality but ignores case differences.

- Both methods return a boolean value.

2. Program Steps

1. Declare two strings.

2. Compare the strings using equals().

3. Compare the strings using equalsIgnoreCase().

4. Print both comparison results.

3. Code Program

public class StringComparisonExample {
    public static void main(String[] args) {
        // Declare two strings for comparison
        String str1 = "hello";
        String str2 = "Hello";
        // Compare strings using equals()
        boolean isEqual = str1.equals(str2);
        // Compare strings using equalsIgnoreCase()
        boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2);
        // Print the results of both comparisons
        System.out.println("Using equals(): " + isEqual);
        System.out.println("Using equalsIgnoreCase(): " + isEqualIgnoreCase);
    }
}

Output:

Using equals(): false
Using equalsIgnoreCase(): true

Explanation:

1. String str1 = "hello": Declares and initializes a String variable str1.

2. String str2 = "Hello": Declares and initializes a String variable str2.

3. boolean isEqual = str1.equals(str2): Compares str1 and str2 using the equals() method, which checks for case-sensitive equality.

4. boolean isEqualIgnoreCase = str1.equalsIgnoreCase(str2): Compares str1 and str2 using the equalsIgnoreCase() method, which ignores case differences.

5. System.out.println("Using equals(): " + isEqual): Prints the result of the equals() method.

6. System.out.println("Using equalsIgnoreCase(): " + isEqualIgnoreCase): Prints the result of the equalsIgnoreCase() method.


Comments