String compareTo()

In java string compareTo() method is used to compare the strings in java. We can compare two strings by use of compareTo() method and it will return an int value. Actually, it compares the string-based of lexicographic. Lexicographic comparisons are like the ordering that one might find in a dictionary.
The return type of compareTo() is int. It returns positive, negative or zero(0) value.

java string compareTo
stringName.compareTo(str)

stringName: The name of the string in which you want to compare with another string.
str: It is a String parameter of compareTo() method. The given string compares with stringName.

class ExampleOfCompareTo
{  
   public static void main(String args[])
   {    
	String string1 = "RAVI";  
	String string2 = "JAVA";  
	String string3 = "WINGS";  
	String string4 = "RAVI";
		
       //8 because Unicode value "RAVI" is greater than "JAVA"  
       System.out.println(string1.compareTo(string2)); 
       // -5 because Unicode value "RAVI" is less than "WINGS"  
       System.out.println(string1.compareTo(string3));
        // 0 because Unicode value are equals 
       System.out.println(string1.compareTo(string4));  
    }
} 

Output:
8
-5
0

How java string compareTo works

This method compares the strings based on the Unicode value of each character in the strings.

  1. If the first string is lexicographically greater than the second string, it returns a positive number. Example: S1 > S2.
  2. If the first string is less than the second string lexicographically, it returns a negative number. Example: S1 < S2.
  3. If the first string is lexicographically equal to the second string, it returns 0. Example: S1 == S2 .

Leave a Comment