Menu
Topics Index
...
`


Strings > String Comparison >
Siva Nookala - 03 Mar 2017
The equals and equalsIgnoreCase are used to compare two Strings and states whether they are equal or not.

The equals is represented as:
boolean equals(String str)
The equals will compare String strwith the invoking String. It returns true if both the strings have same characters in same sequence else it returns false.

The equalsIgnoreCase is represented as:
boolean equalsIgnoreCase(String str)
The equalsIgnoreCase() will compare String str with the invoking String Object. It returns true if both the strings have same characters in same sequence but it ignores the case differences i.e it considers [A-Z]=[a-z], A is same as a and Y is same as y.

Here is the example program demonstrating these methods:
StringComparisonequals and equalsIgnoreCase Demo
class EqualsDemo
{
    public static void main(String arg[])
    {
        String one = "Hyderabad";
        String two = "HYDERABAD";
        String three = "Hyderabad";
        String four = "Kakinada";
        System.out.println(one + " equals " + three + " -- " + one.equals(three));
        System.out.println(one + " equals " + two + " -- " + one.equals(two));
        System.out.println(one + " equals IgnoreCase " + two + " -- "
        + one.equalsIgnoreCase(two));
        System.out.println(one + " equals " + four + " -- " + one.equals(four));    
    }
}
OUTPUT

Hyderabad equals Hyderabad -- true
Hyderabad equals HYDERABAD -- false
Hyderabad equals IgnoreCase HYDERABAD -- true
Hyderabad equals Kakinada -- false

DESCRIPTION

The program consists of four output lines.

  • The first output line is true since each character of the invoking string one is compared and matched with each character of three using equals(). Since both contain "Hyderabad" it returns true
  • The second output line is false since one doesnot match with characters of two(HYDERABAD) due to case difference.
  • The third outputline is true since one(Hyderabad) matches with characters of two(HYDERABAD) even if there is case difference since we are using equalsIgnoreCase().
  • The fourth output is false since the invoking string's each character one(Hyderabad) does not match with each character of four(Kakinada) using equals().

THINGS TO TRY
  • Try with some more example pairs like "window" and "WiNDow". Try both equals and equalsIgnoreCase.

Dependent Topics : replace() Method In Java  Java equals method vs == Operator  toLowerCase() And toUpperCase() Methods In Java 

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.