Syntax: How to write a compareTo() method in Java: Parameter input : str – The compareTo() function in Java accepts only one input String data type. Method Returns: This compareTo() Java method returns an int datatype which is based on the lexicographical comparison between two strings.
returns < 0 then the String calling the method is lexicographically first returns == 0 then the two strings are lexicographically equivalent returns > 0 then the parameter passed to the Java compareTo() method is lexicographically first.
Java String compareTo() method Example: compareTo() Java Example 1: Output Compare To ‘a’ b is : -1 Compare To ‘b’ a is : 1 Compare To ‘b’ b is : 0 Here,
Character a comes before b alphabetically. Hence output is -1 Character b comes after a alphabetically. Hence output is 1 Character b are equivalent, hence output is 0.
You can use method Use “compareToIgnoreCase” in case you don’t want the result to be case sensitive. Let’s understand with a Java compareTo() Example. compareTo() Java Example 2: Output Compare To ‘ROCKSTAR’: -32 Compare To ‘ROCKSTAR’ – Case Ignored: 0
When to use compareTo() method in Java?
Java String 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 alphabetical order. compareTo() Java method does a sequential comparison of letters in the string that have the same position. 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 Let’s understand with Java String compareTo() Example. compareTo() Java Example 3: Output: String 1: Guru1 String 2: Guru2 “Guru1” is lexicographically higher than “Guru2”