String compareTo() Method in Java with Example
What is compareTo() method in Java?
compareTo() method is used to perform natural sorting on string. Natural sorting means the sort order which applies on the object, e.g., lexical order for String, numeric order for Sorting integers, etc.
Lexical order is nothing but alphabetically order. compareTo methods does a sequential comparison of letters in the string that have the same position.
compareTo is defined in interface java.lang.Comparable
Compare To ‘a’ b is : -1
Compare To ‘b’ a is : 1
Compare To ‘b’ b is : 0
Compare To ‘ROCKSTAR’: -32
Compare To ‘ROCKSTAR’ – Case Ignored: 0
When to use CompareTo() method?
CompareTo() is used for comparing two strings lexicographically. Each character of both strings are converted into a Unicode value. However, if both the strings are equal, then this method returns 0 else it only result either negative or positive value.
In this method, if the first string is always lexicographically higher than second string, it returns a positive number.
if a1 > a2, it returns negative number
if a1 < a2, it returns positive number
if a1 == a2, it returns 0
String 1: Guru1
String 2: Guru2
“Guru1” is lexicographically higher than “Guru2”