Java string compareTo() method

    compareTo() method

    The Java string compareTo() method will allow you to compare the provided string with the current string lexicographically. The output may be positive, negative or zero. The Unicode value of each character will be compared to both the strings. There will be three conditions-

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

    Where s1 and s2 are the two strings.

    Syntax-

    public int compareTo(String anotherString)  

    Example-

    public class Simple{  
       public static void main(String args[]){  
          String s1="hello";  
          String s2="hello";  
          String s3="meklo";  
          String s4="hemlo";  
          String s5="flag";  
    
          System.out.println(s1.compareTo(s2));
          System.out.println(s1.compareTo(s3));
          System.out.println(s1.compareTo(s4));
          System.out.println(s1.compareTo(s5));
        }
    }  

    Output-

    Example with empty strings-

    public class Simple{  
        public static void main(String args[]){  
        String s1="hello";  
        String s2="";  
        String s3="meklo";  
    
        System.out.println(s1.compareTo(s2));
        System.out.println(s1.compareTo(s3));
       }
    }  

    Output-

    Java CompareTo method