A Guide to Implementing the Java CompareTo Method

December 07, 2023
A Guide to Implementing the Java CompareTo Method



The Java compareTo method plays a critical role in Java development and helps the developer sort complex objects and define custom sorting logic. Without it, handling complex objects becomes tricky. Hence, it is a must-have tool every Java developer needs to have in their arsenal.

In this guide, we will help you learn with practical examples how to implement the Java compareTo method and why and when to use it.

So, without further ado, let’s begin…

CTABanner2.4

Understanding the Java compareTo Method

A part of the ‘comparable’ interface in Java, the ‘compareTo’ method defines the natural order of objects within a class. Using this method, you can define or sort the custom objects in a desirable and meaningful way to keep confusion at a minimum and make development a breeze.

Below is the syntax of the ‘compareTo’ method:

int compareTo(T o);

Here, ‘T’ represents the type of object. Remember, the Java compareTo method always returns an integer value.

  • Positive if the current object is greater than the parameter object.
  • Negative if the current object is lesser than the parameter object.
  • Zero if the two objects are equal.

Implementing the compareTo Method in Java

Below are the three common use cases of the Java compareTo method.

  • To compare a string with another object.
  • To compare two strings lexicographically.
  • To compare two strings lexicographically ignoring case differences.

1. To compare a String with another Object

Syntax:

int compareTo(Object obj)

Example 1:

// Java code to demonstrate the

// working of compareTo()

public class Cmp1 {

    public static void main(String args[])

    {

        // Initializing Strings

        String str1 = "worldcup";

        String str2 = new String("worldcup");

        String str3 = new String("topplayer");

        // Checking if worldcup string

        // equates to worldcup object

        System.out.print(

            "Difference of worldcup(obj) and worldcup(str) : ");

        System.out.println(str1.compareTo(str2));

        // Checking if worldcup string

        // equates to topplayer object

        System.out.print(

            "Difference of topplayer(obj) and worldcup(str) : ");

        System.out.println(str1.compareTo(str3));

    }

}

Output:

Difference of worldcup(obj) and worldcup(str) : 0

Difference of topplayer(obj) and worldcup(str) : 3

Let’s see another example to better understand how the Java compareTo method works in real time.

Example 2:

public class Book implements Comparable<Book> {

  // parameters of a book

  String book_name;

  String author;

  int year;

  // constructor method to store different values

  public Book(String book_name, String author, int year) {

    this.book_name = book_name;

    this.author = author;

    this.year = year;

  }

  // compareTo() method

  @Override

  public int compareTo(Book anotherBook) {

    if (this.year > anotherBook.year) {

      return 1;

    }

    if (this.year == anotherBook.year) return 0;

    return -1;

  }

  public static void main(String[] args) {

    // Objects of Book class

    Book Java = new Book("Java for Beginners", "John Brown", 2005);

    Book Fundamentals = new Book("Fundamentals of Java", "Anthony Lewis", 2022);

    Book Python = new Book("Learning Python ", "Marry Jacob", 2006);

    // to check if Java's book was released after Python's Book

    System.out.println(Java.compareTo(Python));

    System.out.println(Fundamentals.compareTo(Python));

  }

}

Output:

-1

1

2. To compare Two Strings Lexicographically

Lexicographically means to compare two strings in a dictionary order. Here, the method returns a positive integer if the first string comes before the second, a negative if the first comes after the second, and a zero if both are equal. Let’s see the syntax to better understand how the variant works.

Syntax:

int compareTo(String anotherString)

Example 1:

public class CompareToExample{  

public static void main(String args[]){  

String s1="hello";  

String s2="hello";  

String s3="moon";  

String s4="sparrow";  

String s5="fly";  

System.out.println(s1.compareTo(s2));//0 because both are equal  

System.out.println(s1.compareTo(s3));//-5 because "h" is 5 times lower than "m"  

System.out.println(s1.compareTo(s4));//-11 because "h" is 11 times lower than "s"  

System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f"  

}}

Output:

0

-5

-11

2

3. To compare Two Strings Lexicographically ignoring Case Differences

Like the above variant, the method compares two strings but ignores the case differences. Put plainly, the method treats small and capital letters alike. Now, how can you know whether your syntax is correct and the Java compareTo method is not sensitive to case differences? Simple. See the output.

When comparing two strings the usual way, one in all caps and the other in small alphabets, you will see 0 as the output. However, when the case differences are ignored, you will see a positive or negative integer in the output. Let’s understand its implementation with an example.

Example 1:

public class CompareToExample3  

{  

// main method  

public static void main(String argvs[])  

{  

// input string in uppercase  

String st1 = new String("WORLD CUP FINAL");  

// input string in lowercase  

String st2 = new String("world cup final");  

System.out.println(st1.compareTo(st2));  

}  

}

Output:

-32

Final Word

The Java compareTo method is a powerful tool every developer needs for implementing custom sorting logic for objects in Java. Knowing how the feature works allows you to make development seamless and develop more flexible, user-friendly, and functional apps in Java.

Luckily, the Java compareTo method lets you compare both simple objects like integers and complex custom ones so you can sort your data the right way.

Read more: How to Overcome Silo Mentality and Foster Collaboration in the Workforce

CTABanner2.3



author

admin


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US