The difference between equals() and equalsIgnoreCase() in JAVA

1. Use the equals() method to compare whether two strings are equal. It has the following general form:

boolean equals(Object str)

Here str is a String object used to compare with the calling String object. It returns true if two strings have the same characters and length, otherwise it returns false. This comparison is case-sensitive.

2. In order to perform comparisons that ignore case, you can call the equalsIgnoreCase() method.

When comparing two strings, it will think that AZ and az are the same. Its general form is as follows:

boolean equalsIgnoreCase(String str)

Here, str is a String object used for comparison with the calling String object. It also returns true if the two strings have the same characters and length, false otherwise. The following example illustrates the equals() and equalsIgnoreCase() methods:

// Demonstrate equals() and equalsIgnoreCase().
class equalsDemo {
    public static void main(String args[]) {
        String s1 = "Hello";
        String s2 = "Hello";
        String s3 = "Good-bye";
        String s4 = "HELLO";
        System.out.println(s1 + " equals " + s2 + " -> " +
                s1.equals(s2));
        System.out.println(s1 + " equals " + s3 + " -> " +
                s1.equals(s3));
        System.out.println(s1 + " equals " + s4 + " -> " +
                s1.equals(s4));
        System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +
                s1.equalsIgnoreCase(s4));
    }
}

The output of this program looks like this:

Hello equals Hello -> true
Hello equals Good-bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true

Guess you like

Origin blog.csdn.net/tck001221/article/details/131972972
Recommended