String Comparison in Java


☞We can compare string in java on the basis of content and reference.

☞There are 3 ways to compare string in java.

1. By equals() method
2. By == operator
3. By compareTo() method

equals() Method

☞It compares the original content of the string.

☞String class provides two methods :

1. equals() method 
2. equalsIgnoreCase() method

Example

class EqualsExample{
    public static void main(String args[]){
        
        String s1="Avlokan";
        String s2="Avlokan";
        String s3=new String("Avlokan");
        String s4="Mohan";
        String s5="AVLOKAN";
        
        System.out.println(s1.equals(s2));		
        System.out.println(s1.equals(s3));		
        System.out.println(s1.equals(s4));		
        System.out.println(s1.equals(s5));		
        System.out.println(s1.equalsIgnoreCase(s5));
    
    }
}

Output

true
true
false
false
true

== Operator

☞It compares refernces not values.

Example

class EqualsExample{
    public static void main(String args[]){
        
        String s1="Avlokan";
        String s2="Avlokan";
        String s3=new String("Avlokan");
        String s4=new String("Avlokan");
        
        System.out.println(s1==s2);	
        System.out.println(s1==s3);	
        System.out.println(s3==s4); 
    
    }
}

Output

true
false
false

compareTo() Method

☞It compares values lexicographically and returns an integer value.

☞Suppose str1 and str2 are two string variables.

1. If str1 == str2, then output will be 0
2. If str1 > str2, then output will be positive value
3. If str1 < str2, then output will be negative value

Example

class CompareToExample{
    public static void main(String args[]){
    
        String s1="Avlokan";
        String s2="Avlokan";
        String s3=new String("Avlokan");
        String s4=new String("Avlokan");
        String s5="Mohan";
    
        System.out.println(s1.compareTo(s2));
        System.out.println(s1.compareTo(s3));
        System.out.println(s3.compareTo(s4));
        System.out.println(s1.compareTo(s5));
        System.out.println(s5.compareTo(s1));
    
    }
}

Output

0
0
0
-12
12