How to use equals( ) and equalsIgnoreCase( ) in Java

By: Fazal  

To compare two strings for equality, use equals( ). It has this general form:

boolean equals(Object str)

Here, str is the String object being compared with the invoking String object. It returns true if the strings contain the same characters in the same order, and false otherwise.

The comparison is case-sensitive. To perform a comparison that ignores case differences, call equalsIgnoreCase( ). When it compares two strings, it considers A-Z to be the same as a-z. It has this general form:

boolean equalsIgnoreCase(String str)

Here, str is the String object being compared with the invoking String object. It, too, returns true if the strings contain the same characters in the same order, and false otherwise. Here is an example that demonstrates equals( ) and equalsIgnoreCase( ):

// Demonstrate equals() and equalsIgnoreCase().
class equalsDemo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +
s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " +
s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +
s1.equalsIgnoreCase(s4));
}
}

The output from the program is shown here:
Hello equals Hello -> true
Hello equals Good-bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true




Archived Comments

1. isucuro
View Tutorial          By: isucuro at 2017-09-04 11:23:18

2. xevuqubutixux
View Tutorial          By: xevuqubutixux at 2017-09-03 12:30:53

3. anasiqigaxeb
View Tutorial          By: anasiqigaxeb at 2017-09-03 12:24:55

4. ifukeidau
View Tutorial          By: ifukeidau at 2017-09-03 12:19:15

5. Thanks for sharing this awesome article. It save my day.
View Tutorial          By: actgeek michae at 2016-01-04 12:07:30

6. Nice article.
View Tutorial          By: Govardhan rao Ganji at 2015-11-03 07:55:51

7. Nice Post. Find more on java on my blog - http://javacodeimpl.blogspot.com/
View Tutorial          By: Kumar Bhatia at 2014-05-18 04:30:16

8. Nice one , Compailed no Errors ... but when executing it doesnt work ... something wrong with main r
View Tutorial          By: Diamant at 2012-12-04 00:17:11

9. nice article but can more example
View Tutorial          By: sandi at 2012-10-18 13:26:10

10. Its awesome
View Tutorial          By: Ranjitha at 2012-08-02 10:21:59

11. good thanks!!
View Tutorial          By: LSS at 2011-02-10 22:45:42


Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial