Java-Comparing Length

Comparing Length

It should be carefully noted here equals( ), equalsIgnoreCase( ) methods enable us to check whether two strings are identical or not. However, in some situations, we may wish to test whether one string is greater than, equal to or less than another string. The compareTo( ) method of the String class is useful in all such situations. This method will return a positive value when the string is greater than the parameter, will return zero when the string is equal to the parameter and it will return a negative value when the string is less than the parameter.

Program

1

Program Source

public class Javaapp {
    
    public static void main(String[] args){
        
        String str1 = new String("abcdefgh");
        String str2 = new String("abcde");
        String str3 = new String("abcdefghijkl");
        String str4 = new String("abcdefgh");
        
        if(str1.compareTo(str2)>0)
        {
            System.out.println("str1 greater than str2");
        }
        if(str1.compareTo(str3)<0)
        {
            System.out.println("str1 less than str3");
        }
        if(str1.compareTo(str4)==0)
        {
            System.out.println("str1 == str4");
        }
   }
}

One thought on “Java-Comparing Length

Leave a Comment