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

By: Fazal Viewed: 184 times  Printer Friendly Format    


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



Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial

Subscribe to Tutorials

Related Tutorials

Archived Comments

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

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

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

4. Nice one , Compailed no Errors ... but when execut
View Tutorial          By: Diamant at 2012-12-04 00:17:11

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

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

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

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

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

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

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