Saturday 19 July 2014

Compare Strings in Java

String class provides below methods to compare strings in java.

1. compareTo (String anotherString)
2. compareToIgnoreCase (String str)
compareTo return a negative integer, zero, or a positive integer as the specified String is greater than, equal to, or less than this String, compareToIgnoreCase also do the same, but ignore the case.

3. equals (Object anObject)
4. equalsIgnoreCase (String anotherString)
Methods return if the specified String is equal to this string. EqualsIgnoreCase do the same, but ignores the case.

Example
public class StringComparison {
    public static void main(String args[]){
        String s1 = "abcd";
        String s2 = "ABCD";
        
        System.out.println("s1 = " + s1);
        System.out.println("s2 = " + s2);

        System.out.println("s1.compareTo(s2) = " + s1.compareTo(s2));
        System.out.println("s1.compareToIgnoreCase(s2) = " + s1.compareToIgnoreCase(s2));
        System.out.println("s1.equals(s2) = " + s1.equals(s2));
        System.out.println("s1.equalsIgnoreCase(s2) = " + s1.equalsIgnoreCase(s2));
 }
}

Output
s1 = abcd
s2 = ABCD
s1.compareTo(s2) = 32
s1.compareToIgnoreCase(s2) = 0
s1.equals(s2) = false
s1.equalsIgnoreCase(s2) = true




                                                             Home

No comments:

Post a Comment