string compareto java

The string compareto java method compares the given string with current string lexicographically. It returns positive number, negative number or 0.

In the event that the first string is lexicographically more greater than second string, it will give a positive number. On the off chance that the first string is not as much as second string lexicographically, it returns negative number and if the first string is lexicographically equal to the second string, it returns 0.

compareTo() method is used to perform natural sorting on a string. Natural sorting implies the sort arrange which applies on the object, e.g., lexical request for String, numeric request for Sorting whole numbers etc.

    if String s1 > String s2, it returns positive number  
    if String s1 < String s2, it returns negative number  
    if String s1 == String s2, it returns 0

Syntax -

    public int compareTo(String StringParam)

Note - StringParam represent string that is to be compared with current string. And this method return type is integer.(Read Also - String replace java )

String CompareTo() method Example -

Here we have five Strings and we are comparing them with each other using compareTo() method.

    public class StringCompareToExample{  
    public static void main(String args[]){  
           String s1="Java";  
           String s2="Java";  
           String s3="Tech";  
           String s4="World";  
           String s5="flag";  
      System.out.println(s1.compareTo(s2));//0 because both are equal  
      System.out.println(s1.compareTo(s3));//-5 because "h" is 5 times lower than "m"  
      System.out.println(s1.compareTo(s4));//-1 because "l" is 1 times lower than "m"  
      System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f"  

Now you guys have fair idea on string compareto java, Kindly let me know understanding and your opinion/doubt in the comment box.

Leave a Comment