0
0
JavaHow-ToBeginner · 3 min read

How to Use compareTo in Java: Syntax and Examples

In Java, compareTo is a method used to compare two objects that implement the Comparable interface. It returns a negative number if the first object is less, zero if equal, and a positive number if greater than the second object. This helps in sorting or ordering objects.
📐

Syntax

The compareTo method is defined in the Comparable interface and has this signature:

  • int compareTo(T other): compares the current object with other.

Return values mean:

  • Negative: current object is less than other.
  • Zero: both objects are equal.
  • Positive: current object is greater than other.
java
public interface Comparable<T> {
    int compareTo(T other);
}
💻

Example

This example shows how to use compareTo with strings and integers to compare their values.

java
public class CompareToExample {
    public static void main(String[] args) {
        String a = "apple";
        String b = "banana";

        int result = a.compareTo(b);
        System.out.println("Comparing '" + a + "' to '" + b + "': " + result);

        Integer x = 10;
        Integer y = 5;
        System.out.println("Comparing " + x + " to " + y + ": " + x.compareTo(y));
    }
}
Output
Comparing 'apple' to 'banana': -1 Comparing 10 to 5: 1
⚠️

Common Pitfalls

Common mistakes when using compareTo include:

  • Not implementing Comparable in custom classes before calling compareTo.
  • Assuming compareTo returns only -1, 0, or 1; it can return any negative or positive integer.
  • Using == to compare objects instead of compareTo or equals.

Always ensure your class implements Comparable and override compareTo properly.

java
class Person implements Comparable<Person> {
    String name;

    Person(String name) {
        this.name = name;
    }

    // Wrong: missing compareTo implementation
    // public int compareTo(Person other) { return 0; }

    // Correct:
    public int compareTo(Person other) {
        return this.name.compareTo(other.name);
    }
}

// Usage:
// Person p1 = new Person("Alice");
// Person p2 = new Person("Bob");
// System.out.println(p1.compareTo(p2));
📊

Quick Reference

Return ValueMeaning
Negative numberCurrent object is less than the argument
ZeroCurrent object is equal to the argument
Positive numberCurrent object is greater than the argument

Key Takeaways

Use compareTo to compare objects that implement Comparable for sorting or ordering.
compareTo returns negative, zero, or positive integers to show order relation.
Always implement Comparable and override compareTo in your custom classes.
Do not assume compareTo returns only -1, 0, or 1; it can be any negative or positive number.
Use compareTo instead of == to compare object values.