top

Search

Java Tutorial

.

UpGrad

Java Tutorial

CompareTo in Java

Introduction

The compareTo() method is crucial in comparing strings lexicographically in Java. It is a part of the Comparable interface and is implemented by the String class.

compareTo() in Java allows developers to determine the relative order of two strings based on their Unicode values. Programmers can effectively sort and organize strings in various applications by understanding how compareTo() works and its return values.

Read on to learn more about compareTo() in Java with examples.

Overview

The compareTo() method in Java compares objects and determines their relative order. It returns an integer value for the comparison. It is commonly used for sorting and ordering objects. 

Syntax of compareTo()

Let’s address the question: How does compareTo work in Java?

The syntax of the compareTo() method is:

public int compareTo(Object obj)

The compareTo() method takes a single parameter, obj, representing the object to be compared with the current object. It is typically of the same class as the object on which the method is called, but it can also be of a superclass or interface type.

compareTo() Return Values

The Java compareTo() method compares two strings lexicographically and returns an integer value with the following characteristics:

  • Positive number: If the current string is lexicographically larger than the specified string. The magnitude represents the difference between the Unicode values of the first non-matching characters.

  • Negative number: If the current string is lexicographically smaller than the specified string. The magnitude represents the difference between the Unicode values of the first non-matching characters.

  • Zero: If the strings are lexicographically equal.

For example, comparing "baseball" and "basketball" with compareTo() returns a positive value. Comparing "baseball" and "basketball" returns a negative value. Comparing two equal strings like "baseball" and "baseball" returns 0, indicating their lexicographic equality.

Internal implementation

The internal implementation of compareTo() varies depending on the class implementing it. Generally, the method compares certain fields or properties of the objects to determine their order. The exact logic for comparison is specific to the class and its natural ordering requirements.

It is important to note that the compareTo() method should ensure consistency with the equals() method, meaning if a.compareTo(b) returns zero, then a.equals(b) should also return true. Additionally, the method should throw a ClassCastException if the specified object cannot be compared to the current object's type.

Here's an example of how compareTo() can be implemented for a custom Person class based on the person's age:

In the above program, the compareTo() method compares the ages of two Person objects and uses the Integer.compare() method to determine the comparison result. The main method creates two Person objects, person1 and person2, with different names and ages. It then calls the compareTo() method on person1 and passes person2 as the argument. The comparison result is stored in the comparisonResult variable.

Based on the comparison result, the program prints a message indicating whether person1 is younger, older, or of the same age as person2. The getName() method is added to retrieve the name of a Person object for printing purposes.

Code:

public class Person implements Comparable<Person> {
    private String name;
    private int age;
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public int compareTo(Person other) {
        return Integer.compare(this.age, other.age);
    }
    public static void main(String[] args) {
        Person person1 = new Person("Alice", 25);
        Person person2 = new Person("Bob", 30);
        int comparisonResult = person1.compareTo(person2);
        if (comparisonResult < 0) {
            System.out.println(person1.getName() + " is younger than " + person2.getName());
        } else if (comparisonResult > 0) {
            System.out.println(person1.getName() + " is older than " + person2.getName());
        } else {
            System.out.println(person1.getName() + " and " + person2.getName() + " are of the same age.");
        }
    }
    public String getName() {
        return name;
    }
}

Java String.compareTo() Method

CompareTo() in Java compares two strings lexicographically, indicating their relative order with an integer value. Java uses it for sorting and arranging strings based on Unicode values.

Using int compareTo(Object obj)

In the above example, the Book class implements the Comparable interface without using generics. The compareTo(Object obj) method is overridden to compare the titles of two Book objects using the String class's compareTo() method.

Within the compareTo() method, we first check if the provided object obj is an instance of Book. If it is, we cast it to Book type and compare the titles using String's compareTo method. If obj is not a Book object, we throw a ClassCastException.

The main method demonstrates the usage of compareTo by creating two Book objects, book1 and book2, and comparing their titles. The result is then used to print a message indicating whether book1 comes before, after, or has the same title as book2.

Code:

public class Book implements Comparable {
    private String title;
    private String author;
    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }
    @Override
    public int compareTo(Object obj) {
        if (obj instanceof Book) {
            Book other = (Book) obj;
            return this.title.compareTo(other.title);
        }
        throw new ClassCastException("Cannot compare Book object with a different type.");
    }
    public static void main(String[] args) {
        Book book1 = new Book("1984", "George Orwell");
        Book book2 = new Book("To Kill a Mockingbird", "Harper Lee");
        int comparisonResult = book1.compareTo(book2);
        if (comparisonResult < 0) {
            System.out.println(book1.getTitle() + " comes before " + book2.getTitle());
        } else if (comparisonResult > 0) {
            System.out.println(book1.getTitle() + " comes after " + book2.getTitle());
        } else {
            System.out.println(book1.getTitle() + " and " + book2.getTitle() + " have the same title.");
        }
    }
    public String getTitle() {
        return title;
    }
}

Using int compareTo(String anotherString)

In the program above, the compareTo(String anotherString) method is used to compare strings str1 and str2, str1 and str3, and str2 and str1. The compareTo method returns an integer value representing the lexicographical comparison result between the strings.

The main method demonstrates the usage of compareTo by comparing the strings and printing the comparison results. The output will show how the strings are ordered lexicographically. In this example, str1 is lexicographically smaller than str2, so result1 is -1. str1 is lexicographically equal to str3, so result2 is 0. str2 is lexicographically greater than str1, so result3 is 1.

Code:

public class upGradTutorials {
    public static void main(String[] args) {
        String str1 = "apple";
        String str2 = "banana";
        String str3 = "apple";
        int result1 = str1.compareTo(str2);
        int result2 = str1.compareTo(str3);
        int result3 = str2.compareTo(str1);
        System.out.println("Comparison result between \"" + str1 + "\" and \"" + str2 + "\": " + result1);
        System.out.println("Comparison result between \"" + str1 + "\" and \"" + str3 + "\": " + result2);
        System.out.println("Comparison result between \"" + str2 + "\" and \"" + str1 + "\": " + result3);
    }
}

Using int compareToIgnoreCase(String str)

In this example, we have three strings: str1 as "apple", str2 as "Apple", and str3 as "banana". We use the compareToIgnoreCase(String str) method to compare these strings while ignoring case sensitivity. The main method demonstrates the usage of compareToIgnoreCase by comparing the strings and printing the comparison results. The output will show the comparison results while ignoring the case sensitivity.

In this program, str1 and str2 are lexicographically equal, so result1 is 0. str1 is lexicographically smaller than str3, so result2 is -1. Similarly, str2 is lexicographically smaller than str3, so result3 is -1. The case of the letters in the strings is ignored during the comparison.

public class upGradTutorials {
    public static void main(String[] args) {
        String str1 = "apple";
        String str2 = "Apple";
        String str3 = "banana";
        int result1 = str1.compareToIgnoreCase(str2);
        int result2 = str1.compareToIgnoreCase(str3);
        int result3 = str2.compareToIgnoreCase(str3);
        System.out.println("Comparison result between \"" + str1 + "\" and \"" + str2 + "\": " + result1);
        System.out.println("Comparison result between \"" + str1 + "\" and \"" + str3 + "\": " + result2);
        System.out.println("Comparison result between \"" + str2 + "\" and \"" + str3 + "\": " + result3);
    }
}

Java String compareTo(): empty string

In the program above, str1 is an empty string (""), and str2 is "apple". The compareTo() method is used to compare these two strings. The compareTo() method returns an integer value that indicates the lexicographic comparison result between the strings.

If the result is less than 0, str1 comes before str2 in lexicographical order. If the result is greater than 0, str1 comes after str2. If the result is 0, it means that both strings are equal. In this example, since str1 is an empty string and str2 is not, the result of str1.compareTo(str2) will be negative (result < 0). Therefore, the code will print the following message:

Code:

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

Java String compareTo(): Case Sensitive

In the above example, str1 is "apple" and str2 is "Apple". The compareTo() method is used to compare these two strings. The compareTo() method performs a lexicographic comparison between these two strings, considering the Unicode values of the characters. It is a case-sensitive comparison, meaning that uppercase letters are considered to have a lower value than lowercase letters.

The compareTo() method returns an integer value that represents the comparison result. If the result is less than 0, str1 comes before str2 in lexicographical order. If the result is greater than 0, str1 comes after str2. If the result is 0, it means that both strings are equal.

In this case, since lowercase letters have higher Unicode values than uppercase letters, the result of str1.compareTo(str2) will be positive (result > 0).

Code:

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

Java String compareTo(): NullPointerException

In this example, we compare a string str1 with a null string str2 using the compareTo() method. Since str2 is null, invoking a method on it will result in a NullPointerException. The catch block catches the exception and prints the error message.

Java String compareTo(): ClassCastException

In the main method, we have a String variable str1 with the value "apple" and an Integer variable num with the value 123. We attempt to compare str1 with num using the compareTo() method.

However, we try to cast num to String using (String) num, which is incompatible since num is an Integer object, not a String. This leads to a ClassCastException being thrown at runtime.

Check if two Strings are Equal

In this example, the compareTo() method compares str1 and str2. The result is stored in the result variable. If result is equal to 0, it means the strings are equal. The code then prints the appropriate message based on the comparison result.

However, this is an indirect method, and it is important to note that using equals() or equalsIgnoreCase() methods is generally more straightforward and recommended for checking string equality, as they are specifically designed for that purpose.

Code:

public class upGradTutorials {
    public static void main(String[] args) {
        String str1 = "apple";
        String str2 = "Apple";
        int result = str1.compareTo(str2);
        if (result == 0) {
            System.out.println("The strings are equal");
        } else {
            System.out.println("The strings are not equal");
        }
    }
}

Conclusion

The compareTo() method in Java is a powerful tool for comparing strings or Integer objects. It allows developers to determine the lexicographic or numerical order of two values. Programmers can effectively sort and order data based on specific criteria by understanding its behavior and usage.

It provides a convenient way to implement comparison logic and make informed decisions in Java programming. You can check out courses and tutorials at upGrad to learn about what is compare() in Java and how to use it, 

FAQs

1. What is compareTo() int Java?

The integer compareTo() method belongs to the Integer class in java.lang package. It is used to compare two integer objects based on their numeric values.

2. Is overriding compareTo() method in Java allowed?

Yes, overriding the compareTo() method in Java is allowed. It allows customizing the comparison behavior of objects for sorting and ordering. 

3. What does the return value of compareTo() represent?

CompareTo() in Java facilitates lexicographic string comparisons, providing valuable information about the relative order of the strings.

Leave a Reply

Your email address will not be published. Required fields are marked *