Strings in Java can be compared on the basis of content and reference. It is used in sorting(by compareTo method), reference matching( by == operator) and authentication(by equals() method).
There are mainly three methods listed down below to compare strings in java.
By == operator
The == operator compares references instead of values.
Code:
class javaComparison{
public static void main(String args[]){
String s1="Sandeep";
String s2="Sandeep";
String s3=new String("Sandeep");
System.out.println(s1==s2);// Its true because of referring to same instance)
System.out.println(s1==s3);//Its false because s3 is pointing to instance created in nonpool)
}
}
By equals() method
It compares the original content of and values of the string for equality.
There are two methods provided by the String class.
public boolean equals(Object another): It compares this string to the specified object.
Code:
Class javaComparison{
public static void main(String args[]){
String s1="Sandeep";
String s2="Sandeep";
String s3=new String("Sandeep");
String s4="Rahul";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}
public boolean equalsIgnoreCase(String another): It Compares this String to another String, ignoring case.
class javaComparison{
public static void main(String args[]){
String s1="Sandeep";
String s2="SANDEEP";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s2));//true
}
}
By compareTo() Method
It compares values lexicographically(when two strings have the same length and the same value at same position) and returns an integer that describes if the first string is equal to, less than or greater than the second string.
Let's say a1 and a1 are two strings. If:
a1 == a2 :0
a1 > a2 :Positive value
a1 < a2 :Negative value
class javacomparison{
public static void main(String args[]){
String s1="Sandeep";
String s2="Sandeep";
String s3="Rahul";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}