String comparisons methods in Java

Following are the string comparison methods in java.

1. equals() method.

String class overrides the equals ( ) method of the Object class. It compares the content of the two string object and returns the boolean value accordingly. If both strings are the same then returns β€œtrue” else β€œfalse β€œ, equals ( ) method compares actual contents of two String objects. It differentiates Upper case and Lower case letters.

Example

You can find the code here

2. Using β€œ= =β€œ operator:

 In java,β€œ = = β€œ compares the references not the actual contents of the String object. We can also compare two strings using β€œ= =β€œ. 

Example

String str1=β€œHello β€œ  
String str2=β€œhello”  
String Str3 =β€œHello” 

If (str1= =str2); // returns true 
If (str1 == str3); // returns true 

3. equalsIgnoreCase

It compares strings that ignore the case of contents while comparing. It returns true if str1=str2, ignoring the case of characters. If both strings are the same then returns β€œtrue” else β€œfalse β€œ. 

Example

 String str1=β€œHelloβ€œ  
 String str2=β€œhello”  
 str1.eqaulsIgnoreCase (str2); //returns true  

4. compareTo( )

It compares two Strings and returns an int value. It returns value 0 (zero), if str1 is equals to str2. It returns value negative, if str1 < str2. It returns value positive, if str1 > str2This method behaves exactly like the first method if the argument object is actually a String object; otherwise, it throws a ClassCastException.

int compareTo (String str2)  
int compareTo(Object object) 

Here, I have added few string examples which can help you to understand string comparison statements in a better way.

Example 1

You can find the code here

Rutu Shah