Using String.equals() to Compare two Strings

Introduction to equals() method in String


The equals method itself, suggest that it can compare two objects whether they are completely equal or not with respect to the case of the letters (UPPER/lower). This method being the method of the java.lang.Object, the super class of all the classes, can be called from a String object. It takes, java.lang.Object as parameter and compares it with the String object (here) on which it is called.

class StringEquals
{
public static void main(String args[])
{
// Create strings
String st="This is text to be compared.";
String st1="This is text to be compared.";
if(st.equals(st1))
{
System.out.println("st is equal to st1");
}

// Create another string
String st2="This is text TO BE COMPARED.";


if(st.equals(st2))
{
// Will never be reached
System.out.println("st is equal to st2");

}
if(st.equalsIgnoreCase(st2))
{

// Will be printed
System.out.println("st is equal ignoring case to st2");

}
}
}

Explaining String equals(Object) and equalsIgnoreCase(String)


 st.equals(st1): Compares st and st1 with respect to the case i.e. including the case, not ignoring it.

st.equalsIgnoreCase(st2): Compares st with respect to st2 ignoring the case of the letters in both the strings.

------------------------------------
Output
------------------------------------

st is equal to st1
st is equal ignoring case to st2