equals() and equalsIgnoreCase():
Both are used to compare two strings for equality and both methods are of String class.
equals() general form:
boolean equals(Object str)
It returns true if the invoking string and the string passed in the equals function contains the same characters otherwise it returns false. Both strings must be in same case( Case-sensitive).
equalsIgnoreCase() general form:
boolean equalsIgnoreCase(String str)
It works same as equals() method but it is not case-sensitive.
Example:
class StrComp {
public static void main(String args[]) {
String str1 = "Java";
String str2 = "Java";
String str3 = "Ajax";
String str4 = "JAVA";
System.out.println(str1 + " equals " + str2 + " -> " + //return true as str1 and str2 cotains same data
str1.equals(str2));
System.out.println(str1 + " equals " + str3 + " -> " + //return false as str1 and str3 cotains different data
str1.equals(str3));
System.out.println(str1 + " equals " + str4 + " -> " + //return false as str1(Java) is different from str4(JAVA)
str1.equals(str4));
System.out.println(str1 + " equalsIgnoreCase " + str4 + " -> " +
str1.equalsIgnoreCase(str4));
}
}
Output:
Java equals Java -> true
Java equals Ajax -> false
Java equals JAVA-> false
Java equalsIgnoreCase JAVA -> true
0 Comment(s)