There are three ways to compare string in java:
- By equals() method
- By = = operator
- By compareTo() method
1) String compare by equals() method
The String equals() method compares the original content of the string. It compares values of string for equality. String class provides two methods:
- public boolean equals(Object another) compares this string to the specified object.
- public boolean equalsIgnoreCase(String another) compares this String to another string, ignoring case.
class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}
Output
true
true
false
class Teststringcomparison2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s2));//true
}
}
Output:
false
true
2) String compare by compareTo() method
The java string compareTo() method compares the given string with current string lexicographically. It returns positive number, negative number or 0. It compares strings on the basis of Unicode value of each character in the strings.
- if s1 > s2, it returns positive number
- if s1 < s2, it returns negative number
- if s1 == s2, it returns 0
public class CompareToExample{
public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="meklo";
System.out.println(s1.compareTo(s2));//0 because both are equal
System.out.println(s1.compareTo(s3));//-
5 because "h" is 5 times lower than "m"
}}
Output
0
-5