Wednesday, 13 December 2017

String comparision in Java

 We have methods like equals() to compare the string literals but it is case sensitive and it will check whether two string have same characters in order. And also we have equalsIgnorecase() method to compare the two string and it omits case sensitivity. And also we have compareTo() method amd it is generally used for sorting of collections.

We will see some important compare methods on strings in java below.


public class StringCompareTest {

    public static void main(String[] args) {

        //by Equals method
        String string1 = "equal";
        String string2 = "equal";
        String string3 = new String("equal");
        String s4 = string3.intern();
        StringBuffer stringBuffer = new StringBuffer(string1);
        StringBuilder stringBuilder = new StringBuilder(string1);
        System.out.println(string1.equals(string2));//true
        System.out.println(string1.equals(string3));//true
        System.out.println(string2.equals(string3));//true
        System.out.println(string2.equals(stringBuffer));//false
        System.out.println(string3.equals(stringBuffer));//false
        System.out.println(string2.equals(stringBuilder));//false
        System.out.println(string3.equals(stringBuilder));//false
        System.out.println(stringBuffer.equals(stringBuilder));//false
      
        System.out.println("===================================");
        //by == method
        System.out.println(string1==string2);//true
        System.out.println(string1==string3);//false
        System.out.println(string2 == string3);//false
        System.out.println(s4 == string1);//true
        System.out.println(s4 == string2);//true
        System.out.println(s4 == string3);//false
        System.out.println("===================================");
        System.out.println("compare to");
        //by compareTo method
        String string11 = "equal";
        String string21 = "notequal";
        String string31 = new String("moreequal");
        String string41 = new String("abcmoreequal");
        String string51 = "notequal";
        //s1 ==s2 then 0, s1>s2 then +ve, s1<s2 then -ve
        System.out.println(string11.compareTo(string21));//-9 because n is 9th letter after e
        System.out.println(string11.compareTo(string31));//-8 because n is 8th letter after e
        System.out.println(string21.compareTo(string31));//1 because n is 1st letter after m
        System.out.println(string21.compareTo(string41));//13 because m is 12th letter after a
        System.out.println(string21.compareTo(string51));//0 both are same
    }

}


Output:

true
true
true
false
false
false
false
false
===================================
true
false
false
true
true
false
===================================
compare to
-9
-8
1
13
0

No comments:

Post a Comment