Java String compareTo() Method
compareTo() method is used to compare the two specified Strings based on the alphabetical order(lexicographical order) of their characters.It returns positive number ,negative number or 0 Syntax:
public int compareTo(String anotherString)Parameters: anotherString: the String to be compared with the current String Returns: An integer value based on the case. compare two Strings i.e. s1 and s2 if s1 > s2, it returns positive number if s1 < s2, it returns negative number if s1 == s2, it returns 0 Java String compareTo() Example 1:
public class CompareToEx1 { public static void main(String args[]){ String s1="tutorial"; String s2="Tutorial"; String s3="tootorial"; String s4="tutorial"; String s5="tooturial"; System.out.println(s1.compareTo(s2)); System.out.println(s1.compareTo(s3)); System.out.println(s1.compareTo(s4));//0 because both are equal System.out.println(s1.compareTo(s5)); } }Output:
32 6 0 6Java String compareTo() Example 2:
public class CompareToEx2 { public static void main(String[] args) { //compare a String String str = "Java TutorialAndExample"; System.out.println("Compare To : " + str.compareTo("JAVA TUTORIALANDEXAMPLE")); //Compare a String with Ignore case System.out.println("Compare To : " + str.compareToIgnoreCase("JAVA TUTORIALANDEXAMPLE")); } }OUTPUT:
Compare To : 32 Compare To : 0Java String compareTo() Example 3:
public class CompareToEx3 { public static void main(String[] args) { String s1,s2,s3,s4; s1 = "tutorial"; s2 = "tutorial2"; s3 = "TUTORIAL"; System.out.println("String 1: " + s1); System.out.println("String 2: " + s2); System.out.println("String 3: " + s3); // Compare the strings s1 and s2. int S = s1.compareTo(s2); // Show the results of the comparison. if (S < 0) { System.out.println(s1 +" is lexicographically greater than " + s2 ); //compare the string s1 and s3 int s = s1.compareTo(s3.toLowerCase()); if (s < 0) { System.out.println( s1 + " is lexicographically greater than " + s3 ); } else if (s == 0) { System.out.println(s1 + " is lexicographically equal to " + s3 ); } else if (s > 0) { System.out.println( s1 + " is lexicographically less than " + s3 ); } } else if (S == 0) { System.out.println(s1 + " is lexicographically equal to " + s2 ); } else if (S > 0) { System.out.println( s1 + " is lexicographically less than " + s2 ); } }Output:
String 1: tutorial String 2: tutorial2 String 3: TUTORIAL "tutorial" is lexicographically greater than "tutorial2" "tutorial" is lexicographically equal to "TUTORIAL"