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:
1 2 3 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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:
1 2 3 4 5 6 |
32 6 0 6 |
Java String compareTo() Example 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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:
1 2 3 4 |
Compare To : 32 Compare To : 0 |
Java String compareTo() Example 3:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
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:
1 2 3 4 5 6 7 |
String 1: tutorial String 2: tutorial2 String 3: TUTORIAL "tutorial" is lexicographically greater than "tutorial2" "tutorial" is lexicographically equal to "TUTORIAL" |