Java String equals() and equalsIgnoreCase() Example

  1. boolean equals(String str): Case sensitive comparison
  2. boolean equalsIgnoreCase(String str): Case insensitive comparison
To compare two strings for equality, use equals(). It has this general form:
boolean equals(Object str)
To perform a comparison that ignores case differences, call equalsIgnoreCase(). When it compares two strings, it considers A-Z to be the same as a-z. It has this general form:
boolean equalsIgnoreCase(String str)

Java String equals() and equalsIgnoreCase() Example

Here is an example that demonstrates  equals()  and  equalsIgnoreCase():
 // 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 from the program is shown here:
Hello equals Hello ->
true Hello equals Good-bye ->
false Hello equals HELLO ->
false Hello equalsIgnoreCase HELLO ->
true 

Reference


Comments