GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Java Tutorial
  • Advanced Java
  • Interview Questions
  • Exercises
  • Examples
  • Quizzes
  • Projects
  • Cheatsheet
  • DSA in Java
  • Java Collection
  • Collections.sort()
  • Arrays.sort()
  • Introduction3 min read
  • Variables2 min read

This view

  • Original page
  • New address

GeezerVison is showing www.geeksforgeeks.org — Java Comparable Interface - GeeksforGeeks

geeksforgeeks
search icon
  • Courses
  • Tutorials
  • Interview Prep
  • Java Tutorial
  • Advanced Java
  • Interview Questions
  • Exercises
  • Examples
  • Quizzes
  • Projects
  • Cheatsheet
  • DSA in Java
  • Java Collection

Java Comparable Interface

Last Updated : 1 Oct, 2026

The Comparable interface in Java is used to define the natural ordering of objects of a class. It enables objects to be compared and sorted automatically without using an external Comparator.

  • It contains the compareTo() method, which compares the current object with another object.
  • It is commonly used with Collections.sort() and Arrays.sort() for sorting custom objects.

Example: Sorting By Id

Java
import java.util.*;

class Student implements Comparable<Student> {
    int id;
    String name;

    Student(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public int compareTo(Student other) {

        // Null safety check
        if (other == null) {
            throw new NullPointerException("Cannot compare with null");
        }

        // Safe comparison (avoids integer overflow)
        return Integer.compare(this.id, other.id);
    }

    @Override
    public String toString() {
        return id + "-" + name;
    }
}

public class ComparableExample {
    public static void main(String[] args) {

        List<Student> students = new ArrayList<>();
        students.add(new Student(3, "Alice"));
        students.add(new Student(1, "Bob"));
        students.add(new Student(2, "Charlie"));

        Collections.sort(students);

        System.out.println(students);
    }
}

Output
[1-Bob, 2-Charlie, 3-Alice]

Explanation:

  • Student implements Comparable<Student> and overrides compareTo() to define the sorting logic.
  • compareTo() returns a negative, zero, or positive value to indicate order.
  • Collections.sort(students) sorts the list automatically using the natural order defined in compareTo().
  • Output shows the students sorted by ID in ascending order.

Syntax

class MyClass implements Comparable<MyClass> {
@Override
public int compareTo(MyClass obj) {
// comparison logic
return 0;
}
}

compareTo() Return Values

  • Returns a negative value if the current object is smaller than the specified object.
  • Returns 0 if both objects are equal.
  • Returns a positive value if the current object is greater than the specified object.

Example: Sorting by Marks

Java
import java.util.*;

class Student implements Comparable<Student> {
    String name;
    int marks;

    Student(String name, int marks) {
        this.name = name;
        this.marks = marks;
    }

    @Override
    public int compareTo(Student other) {
          return Integer.compare(this.marks, other.marks);// ascending order by marks
    }

    @Override
    public String toString() {
        return name + ": " + marks;
    }
}

public class ComparableExample {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student("Alice", 85));
        students.add(new Student("Bob", 92));
        students.add(new Student("Charlie", 78));

        Collections.sort(students);

        for (Student s : students) {
            System.out.println(s);
        }
    }
}

Output
Charlie: 78
Alice: 85
Bob: 92

Explanation:

  • Defines natural order by marks using compareTo().
  • Collections.sort() automatically arranges elements in ascending order.
  • The toString() method is used to print objects in a readable format.

Advantages of Comparable Interface

  • Natural Ordering: Defines the default ordering of objects using the compareTo() method.
  • Easy Sorting: Allows custom objects to be sorted directly using utilities such as Collections.sort() and Arrays.sort().
  • Works with Sorted Collections: Helps maintain ordering when objects are used in collections such as TreeSet and as keys in TreeMap.
  • Encapsulated Comparison Logic: Keeps the natural comparison logic within the class itself, avoiding a separate Comparator for the default ordering.
Comment

Explore

    Basics
    • Introduction3 min read
    • Variables2 min read
    • Data Types7 min read
    • Operators7 min read
    • Decision Making5 min read
    • Methods7 min read
    • Arrays7 min read
    • Strings5 min read
    OOP & Interface
    • Introduction6 min read
    • Constructors6 min read
    • Encapsulation3 min read
    • Inheritance8 min read
    • Polymorphism5 min read
    • Abstraction5 min read
    • Interfaces8 min read
    Collections
    • Collection class9 min read
    • Collection Interface5 min read
    • List Interface8 min read
    • Set Interface5 min read
    • Queue Interface5 min read
    • Map Interface in Java6 min read
    • Iterator4 min read
    Advance Java Concepts
    • Exception handling6 min read
    • Java Multithreading Tutorial3 min read
    • Synchronization in Java9 min read
    • File handling6 min read
    • Method References3 min read
    • Java 8 Stream Tutorial7 min read
    • Memory Management4 min read
    • Garbage Collection in Java6 min read
    • Networking6 min read
    • JDBC5 min read
    Practice Java
    • Interview Questions15+ min read
    • Programs6 min read
    • Practice Problems5 min read
    • Quiz1 min read
    • Project Ideas15+ min read
    Courses
    • Java Backend Course2 min read
    • Placement 360 Course2 min read
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.