Interview Q&A / Java

BeginnerQuick answer1 min readUpdated 3 Oct 2026

What is the difference between Comparable and Comparator in Java?

SHORT ANSWER

Comparable defines one natural order inside the class itself through compareTo. Comparator is a separate object with a compare method, so you can define many different orderings without changing the class.

Explain it simply

Students in a class have a natural order, say by roll number, which belongs to the student record itself: that is Comparable. But the teacher may also line them up by height for a photo, or by marks for a result: those outside rules are Comparators.

Example

java
import java.util.*;

class Student implements Comparable<Student> {
    int roll; String name;
    Student(int roll, String name) { this.roll = roll; this.name = name; }
    public int compareTo(Student o) { return Integer.compare(roll, o.roll); }  // natural order
}

List<Student> list = new ArrayList<>(List.of(new Student(3, "Asha"), new Student(1, "Zoya")));
Collections.sort(list);                                        // by roll: Zoya, Asha
list.sort(Comparator.comparing(s -> s.name));                  // by name: Asha, Zoya

What to say in the interview

"Comparable is in java.lang and has compareTo(T). The class has only one natural ordering, and it must modify the class. Comparator is in java.util and has compare(T, T). I can create as many as I like, and even sort classes I cannot edit, such as String by length. In Java 8, I build comparators with Comparator.comparing and thenComparing."

Common mistakes

  • Writing a.roll - b.roll in compareTo, which can overflow for big values. Use Integer.compare.

#java#collections#sorting

Related questions

Practise more Java questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Java quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.