Google News
logo
Java String Comparison
String Comparison
We can compare string in java on the basis of content and reference. It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by = = operator). 

So, there are three ways to compare strings in java:
1. By compareTo() method
2. By = = operator
3. By equals() method

1. compareTo() method:
The compareTo() method is used to compare two strings lexicographically, and to know which string is bigger or smaller. Each character of both the strings is converted into a Unicode value for comparison. This should be used as: s1.compareTo(s2). The character sequence represented by this String object (s1) is compared lexicographically to the character sequence represented by the argument string (s2). This method returns integer value like: 

Zero: if s1 is equal to s2, then this method returns zero.
Positive value: if s1 is greater than s2, then this method returns positive integer value. 

Negative value: if s1 is smaller than s2, then this method returns negative value.
CompareTo and compareToIgnoreCase program
public class sup 
{ 
public static void main(String args[]) { 
String s1 = new String("Hello"); 
String s2 = new String("hello"); 
if(s1.compareToIgnoreCase(s2)==0) 
System.out.println("Both are same"); 
else if(s1.compareTo(s2)<0) 
System.out.println("s1 is smaller than s2 "); 
else 
System.out.println("s1 is bigger than s2 "); 
} 
}
Output :
Both are same
2. = = operator :
When an object is created by JVM, it returns the memory address of the object as a hexadecimal number, which is called 'object reference. When a new object is created a new reference number is alloted to it. 
 
Hence if we use = = operator for comparing two strings then, it checks whether the reference numbers of these two strings are equal are not. If the reference numbers are equal then it will return true, else it will return false. 
== program
class sup 
{ 
public static void main(String[] args) 
{ 
String s1=new String("freetimelearn"); 
String s2=new String("duragsoft"); 
String s3=new String("freetimelearn"); 
String s4=s1; 
System.out.println(s1.equals(s2)); 
System.out.println(s1.equals(s3)); 
System.out.println(s1==s3); 
System.out.println(s1==s4); 
} 
};
Output :
Output: false true false true
3. equals() method :
The equals() method is used to compare the content of two strings. This should be used as s1.equals(s2). Hence the two strings s1 and s2 are compared. If the two strings are equal then this method returns true else it returns false.
equalsIgnoreCase
class Test 
{ 
public static void main(String... ratan) 
{ 
String str1="ramana"; 
String str2="raji"; 
String str3="ramana"; 
String str4="raji"; 
System.out.println(str1.equalsIgnoreCase(str2));//false 
System.out.println(str1.equalsIgnoreCase(str4));//false 
System.out.println(str2.equals(str4));//false 
System.out.println(str2.equalsIgnoreCase(str4));//true 
} 
};
Output :
falue,falue,falue,true