Java String equalsIgnoreCase()

Java String.equalsIgnoreCase() compares the current string with the specified string in a case-insensitive manner. Learn with examples.

Java String

The Java String.equalsIgnoreCase() compares the current string with the specified string in a case-insensitive manner. Using equalsIgnoreCase(), two strings are considered equal if they are of the same length and corresponding characters in the two strings are equal, ignoring their cases.

A similar method String.equals() compares the strings in a case-sensitive manner.

Never use '==' operator for checking the strings equality. It checks the object references, which is not desirable in most cases.

1. String.equalsIgnoreCase() API

The syntax to use the equalsIgnoreCase() API is as follows:

boolean isEqual = thisString.equalsIgnoreCase( anotherString );

Note that if we pass null as the method argument, the comparison result will be false.

2. String.equalsIgnoreCase() Example

The following Java program demos a few comparisons using the equalsIgnoreCase() API. We can see that passing null returns false. Also, equalsIgnoreCase() returns false when the strings have different content.

Assertions.assertFalse("null".equalsIgnoreCase(null));
Assertions.assertFalse("abc".equalsIgnoreCase("abcd")); //Different strings

Assertions.assertTrue("abc".equalsIgnoreCase("ABC"));
Assertions.assertTrue("ABC".equalsIgnoreCase("AbC"));

3. Difference between equals() and equalsIgnoreCase()

Clearly, the primary difference between equals() and equalsIgnoreCase() APIs is their case sensitivity while performing the comparisons.

  • equals() method makes the case-sensitive comparison.
  • equalsIgnoreCase() method makes the case-insensitive comparison.

Happy Learning !!

Reference: String Java Doc

Sourcecode on Github

Leave a Comment

  1. 4. Difference between equals and equalsIgnoreCase
    Clearly, the difference between equals and equalsIgnoreCase in Java is case-sensitity while performing the string comparisons.

    equals() method does case-insensitive comparison.
    equalsIgnoreCase() method does case-insensitive comparison.

    the above last two line have two methods(equals() , equalsIgnoreCase()) having same meaning ???????is it correct

    Reply

Leave a Comment

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.