Open In App

Java String compareTo() Method with Examples

Last Updated : 26 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Strings in Java are objects that are supported internally by an array only which means contiguous allocation of memory for characters .  Please note that strings are immutable in Java which means once we create a String object and assign some values to it, we cannot change the content. However we can create another String object with the modifications that we want.

The String class of Java comprises a lot of methods to execute various operations on strings and we will be focusing on the Java String compareTo() method in this article.

Java String.compareTo() Method

The Java compareTo() method compares the given string with the current string lexicographically. It returns a positive number, a negative number, or 0. It compares strings based on the Unicode value of each character in the strings.

Example:

Java




public class StringCompareTo {
 
    public static void main(String[] args) {
        String str1 = "Geeks";
        String str2 = "Geeks";
 
        int comparison = str1.compareTo(str2);
 
        if (comparison < 0) {
            System.out.println(str1 + " comes before " + str2 + " lexicographically.");
        } else if (comparison > 0) {
            System.out.println(str1 + " comes after " + str2 + " lexicographically.");
        } else {
            System.out.println(str1 + " and " + str2 + " are lexicographically equal.");
        }
    }
}


Output:

Geeks and Geeks are lexicographically equal.

Syntax

int comparison = str1.compareTo(str2);

Parameters:

  • str1: String 1 for comparison
  • str2: String 2 for comparison

Returns:

  • if string1 > string2, it returns positive number
  • if string1 < string2, it returns negative number
  • if string1 == string2, it returns 0

Exception: It throws following two exceptions:

  • NullPointerException- if the specified object is Null.
  • ClassCastException- if current object can’t be compared with specified object.

Variants of CompareTo() Method

There are three variants of the compareTo() method which are as follows:

  1. using int compareTo(Object obj)
  2. using int compareTo(String AnotherString)
  3. using int compareToIgnoreCase(String str)  

1. int compareTo(Object obj)

This method compares this String to another Object.

Syntax: 

int compareTo(Object obj)

Parameters: 

obj:  the Object to be compared.

Return Value: The value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string.

Example:

Below is the implementation of int compareTo(Object obj):

Java




// Java code to demonstrate the
// working of compareTo()
public class Cmp1 {
    public static void main(String args[])
    {
 
        // Initializing Strings
        String str1 = "geeksforgeeks";
        String str2 = new String("geeksforgeeks");
        String str3 = new String("astha");
 
        // Checking if geeksforgeeks string
        // equates to geeksforgeeks object
        System.out.print(
            "Difference of geeksforgeeks(obj) and geeksforgeeks(str) : ");
        System.out.println(str1.compareTo(str2));
 
        // Checking if geeksforgeeks string
        // equates to astha object
        System.out.print(
            "Difference of astha(obj) and geeksforgeeks(str) : ");
        System.out.println(str1.compareTo(str3));
    }
}


Output

Difference of geeksforgeeks(obj) and geeksforgeeks(str) : 0
Difference of astha(obj) and geeksforgeeks(str) : 6



2. int compareTo(String anotherString) 

This method compares two strings lexicographically. 

Syntax: 

int compareTo(String anotherString)

Parameters: 

anotherString:  the String to be compared.

Return Value: The value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string.

Example:

Below is the implementation of int compareTo(String anotherString):

Java




// Java code to demonstrate the
// working of compareTo()
 
public class Cmp2 {
    public static void main(String args[])
    {
 
        // Initializing Strings
        String str1 = "geeksforgeeks";
        String str2 = "geeksforgeeks";
        String str3 = "astha";
 
        // Checking if geeksforgeeks string
        // equates to geeksforgeeks string
        System.out.print(
            "Difference of geeksforgeeks(str) and geeksforgeeks(str) : ");
        System.out.println(str1.compareTo(str2));
 
        // Checking if geeksforgeeks string
        // equates to astha string
        System.out.print(
            "Difference of astha(str) and geeksforgeeks(str) : ");
        System.out.println(str1.compareTo(str3));
    }
}


Output

Difference of geeksforgeeks(str) and geeksforgeeks(str) : 0
Difference of astha(str) and geeksforgeeks(str) : 6



3. int compareToIgnoreCase(String str)  

This method compares two strings lexicographically, ignoring case differences. 

Syntax:

int compareToIgnoreCase(String str)

Parameters: 

str: the String to be compared.

Return Value: This method returns a negative integer, zero, or a positive integer as the specified String is greater than, equal to, or less than this String, ignoring case considerations.

Example:

Below is the implementation of int compareToIgnoreCase(String str):

Java




// Java code to demonstrate the
// working of compareToIgnoreCase()
 
public class Cmp3 {
    public static void main(String args[])
    {
 
        // Initializing Strings
        String str1 = "geeks";
        String str2 = "gEEkS";
 
        // Checking if geeksforgeeks string
        // equates to geeksforgeeks string
        // case sensitive
        System.out.print(
            "Difference of geeks and gEEkS (case sensitive) : ");
        System.out.println(str1.compareTo(str2));
 
        // Checking if geeksforgeeks string
        // equates to astha string
        // case insensitive
        // using compareToIgnoreCase()
        System.out.print(
            "Difference of geeks and gEEkS (case insensitive) : ");
        System.out.println(str1.compareToIgnoreCase(str2));
    }
}


Output

Difference of geeks and gEEkS (case sensitive) : 32
Difference of geeks and gEEkS (case insensitive) : 0



Exceptions in Java String compareTo() Method

compareTo() method in Java can raise two possible exceptions:

  • NullPointerException
  • ClassCastException

compareTo() NullPointerException

In Java, the compareTo() method throws a NullPointerException if either of the objects being compared is null. This ensures that you explicitly handle null values and prevents unexpected behavior.

Example:

Java




public class cmp5 
// main method 
public static void main(String[] args)  
    
String str = null
   
// null is invoking the compareTo method. Hence, the NullPointerException 
// will be raised 
int no =  str.compareTo("Geeks"); 
   
System.out.println(no); 
}


Output:

Exception in thread "main" java.lang.NullPointerException
    at cmp5.main(cmp5.java:11)

compareTo() ClassCastException

It is a runtime exception and occurs when two objects of incompatible types are compared in the compareTo() method. 

Example:

Java




public class ClassCastExceptionExample {
 
    public static void main(String[] args) {
        Object obj1 = "Hello";
        Object obj2 = 10; // Integer object
 
        // Explicitly cast obj2 to String to force the exception
        int comparison = ((String) obj2).compareTo(obj1); 
        System.out.println("Comparison: " + comparison);
    }
}


Output:

./ClassCastExceptionExample.java:8: error: incompatible types: Object cannot be converted to String
        int comparison = ((String) obj2).compareTo(obj1);  // ClassCastException occurs here

Also Read: 

  1. Compare two Strings in Java
  2. Compare two strings lexicographically in Java
  3. Java Integer compareTo() method

Conclusion

compareTo() function in Java is used to compare two strings or objects lexicographically. It returns a positive, zero, or negative integer. In this tutorial, we have covered this method and discussed its working and exceptions.

Read More Java String Methods

Java String CompareTo() Method- FAQs

How to compare strings in Java?

You can compare strings in Java using the compareTo() method. It accepts two parameters and compare them lexicographically.

What is the difference between the compareTo() method and the equals() method in Java?

equals() method compareTo() method
Used to check if two objects are exactly the same. Used to compare two objects and determine their relative order.

Returns a boolean:

  • true if the objects are considered equal.
  • false otherwise.

Returns an integer:

  • Negative value if the first object is considered “less than” the second.
  • Zero if the objects are considered equal.
  • Positive value if the first object is considered “greater than” the second.

What does compareTo () return in Java?

compareTo() method in Java returns an integer. It can have three possible values:

  • Negative value: When the first object is considered “less than” the second.
  • Zero: When the objects are considered equal.
  • Positive value: When the first object is considered “greater than” the second.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads