string compareto java

The string com­pare­to java method com­pares the giv­en string with cur­rent string lex­i­co­graph­i­cal­ly. It returns pos­i­tive num­ber, neg­a­tive num­ber or 0.

In the event that the first string is lex­i­co­graph­i­cal­ly more greater than sec­ond string, it will give a pos­i­tive num­ber. On the off chance that the first string is not as much as sec­ond string lex­i­co­graph­i­cal­ly, it returns neg­a­tive num­ber and if the first string is lex­i­co­graph­i­cal­ly equal to the sec­ond string, it returns 0.

com­pare­To() method is used to per­form nat­ur­al sort­ing on a string. Nat­ur­al sort­ing implies the sort arrange which applies on the object, e.g., lex­i­cal request for String, numer­ic request for Sort­ing whole num­bers 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 — String­Param rep­re­sent string that is to be com­pared with cur­rent string. And this method return type is inte­ger.(Read Also — String replace java )

String CompareTo() method Example -

Here we have five Strings and we are com­par­ing them with each oth­er 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 com­pare­to java, Kind­ly let me know under­stand­ing and your opinion/​doubt in the com­ment box.