What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

compareTo() method in Java

  • Oct 25, 2023
  • 8 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Nihal Mahansaria
compareTo() method in Java

The compareTo() method in Java is a powerful tool for comparing strings lexicographically. It allows us to determine the order of strings based on their Unicode values. In this comprehensive guide, we will explore the functionality, syntax, and nuances of the compareTo() method, and understand the key differences between compareTo() and the equals() method.

Introduction to the compareTo() Method

The compareTo() method is a built-in method in the Java String class that allows us to compare two strings lexicographically. It is based on the Unicode values of the characters in the strings. By comparing the Unicode values, we can determine the relative order of the strings.

The syntax of the compareTo() method is as follows:

public int compareTo(String str)

 

Here, str is the string to be compared with the current string object. The method returns an integer value, which indicates the result of the comparison.

Comparing Strings with compareTo()

To compare two strings using the compareTo() method, we simply invoke the method on one string and pass the other string as the argument. Let's consider an example:

String str1 = "apple";
String str2 = "banana";
int result = str1.compareTo(str2);

 

In this example, we are comparing the strings "apple" and "banana". The result of the comparison is stored in the result variable.

The Return Value of compareTo()

The compareTo() method returns an integer value that indicates the result of the comparison. The possible return values are as follows:

  • If the current string is lexicographically less than the argument string, compareTo() returns a negative integer.
  • If the current string is lexicographically greater than the argument string, compareTo() returns a positive integer.
  • If the current string is equal to the argument string, compareTo() returns zero.

Let's consider an example:

String str1 = "apple";
String str2 = "banana";
int result = str1.compareTo(str2);

 

In this example, since "apple" comes before "banana" lexicographically, the result will be a negative integer.

Handling Empty Strings with compareTo()

When comparing strings with the compareTo() method, it is important to consider the case where one or both of the strings are empty. In such cases, the method returns the length of the non-empty string. Let's take a look at an example:

String str1 = "apple";
String str2 = "";
int result = str1.compareTo(str2);

 

In this example, since str2 is an empty string, the result will be the length of str1, which is 5.

Case Sensitivity in compareTo()

The compareTo() method considers the case sensitivity of characters when comparing strings. It follows the Unicode values of the characters, taking into account uppercase and lowercase distinctions. Let's explore an example to understand this behavior:

String str1 = "Apple";
String str2 = "apple";
int result = str1.compareTo(str2);

 

In this example, since the Unicode value of 'A' is less than the Unicode value of 'a', the result will be a negative integer.

ClassCastException with compareTo()

In certain cases, when objects of incompatible types are compared using the compareTo() method, a ClassCastException may be thrown. It is important to ensure that the objects being compared are of the same type or implement the Comparable interface. Let's consider an example:

ArrayList<String> list = new ArrayList<>();
list.add("Sehwag");
String str = "Tendulkar";
int result = list.get(0).compareTo(str);

 

In this example, we are comparing a string from an ArrayList with a string literal. Since they are of different types, a ClassCastException will be thrown.

NullPointerException with compareTo()

If a null object is passed as an argument to the compareTo() method, a NullPointerException may be thrown. It is crucial to check for null values before invoking the compareTo() method. Let's see an example:

String str1 = "apple";
String str2 = null;
int result = str1.compareTo(str2);

 

In this example, since str2 is null, a NullPointerException will be thrown when invoking the compareTo() method.

Best Practices for Using compareTo()

When using the compareTo() method, it is recommended to keep the following best practices in mind:

  • Implement the Comparable interface when creating custom classes to enable natural ordering.
  • Provide an equals() method that is consistent with the compareTo() method.
  • Handle null values and incompatible types to avoid NullPointerException and ClassCastException.
  • Consider case sensitivity when comparing strings using compareTo().

Conclusion

In conclusion, the compareTo() method in Java is a powerful tool for comparing strings lexicographically. It allows us to determine the order of strings based on their Unicode values. By understanding its syntax, return values, and best practices, we can leverage this method effectively in our Java programs.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Nihal Mahansaria
As a computer science student with a passion for technology and a drive to learn, I have developed a diverse set of skills in web development, machine learning, and technical content writing. With experience in multiple front-end and back-end frameworks, including Flask and Python, I am able to create scalable and efficient web applications.