Login Here                        

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");
System.out.println("Both are same");
else if(s1.compareTo(s2)<0)
System.out.println("s1 is smaller than s2 ");
System.out.println("s1 is bigger than s2 ");

intput and output

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("freetimestudy");
String s2=new String("duragsoft");
String s3=new String("freetimestudy");
String s4=s1;

intput and 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. 


class Test
public static void main(String... ratan)
String str1="venkat";
String str2="ravi";
String str3="venkat";
String str4="Ravi";

intput and output