String methods – equals() and equalsIgnoreCase()
These methods are used to compare 2 string objects. If both String matches, returns true else false.
Equals():
Equals is used to compare 2 strings and it is case sensitive.
e.g. The Strings “JAVA” and “java” , result will be false.
public class EqualsExample { public static void main(String[] args) { String val1 = new String("JAVA"); String val2 = new String("java"); String val3 = new String("Hello"); String val4 = "Hello"; System.out.println("Comparing val1 and val2 "+val1.equals(val2)); //false System.out.println("Comparing val2 and val3 "+val2.equals(val3)); //false System.out.println("Comparing val3 and val4 "+val3.equals(val4)); //true } }
Output:
Comparing val1 and val2 false
Comparing val2 and val3 false
Comparing val3 and val4 true
Comparing val1 and val2 false
Comparing val2 and val3 false
Comparing val3 and val4 true
equalsIgnoreCase():
This is used to compare 2 strings and it is not case-sensitive.
e.g. The Strings “JAVA” and “java” , result will be true.
public class EqualsIgnoreCaseExample { public static void main(String[] args) { String val1 = new String("JAVA"); String val2 = new String("java"); String val3 = new String("Hello"); String val4 = "Hello"; System.out.println("Comparing val1 and val2 "+val1.equalsIgnoreCase(val2)); //true System.out.println("Comparing val2 and val3 "+val2.equalsIgnoreCase(val3)); //false System.out.println("Comparing val3 and val4 "+val3.equalsIgnoreCase(val4)); //true } }
Output: Comparing val1 and val2 true
Comparing val2 and val3 false
Comparing val3 and val4 true
Comparing val2 and val3 false
Comparing val3 and val4 true
Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.
1 Response
[…] boolean equals(Object anObject) […]