PGoCareerGoCareer prep tools
Home
LoginSign up
  • Java
  • Python
  • AI
  • React
  • Angular
  • PHP
  • Node.js
  • SQL
  • DSA
  • HTML
  • CSS
  • JS
  • Spring
  • ML
  • MongoDB

Java · Theory

Comparable vs Comparator in Java

← All stacks

Theory

217/270

Comparable vs Comparator in Java

Comparable lives inside the class: implement compareTo. That is the natural order — Integer and String already do this. Comparator is a separate class or lambda: compare(a, b). Extra orders without changing the class.

One compareTo per class. Many Comparators possible: by name, by marks, by date. Collections.sort(list) uses Comparable. Collections.sort(list, cmp) uses Comparator.

Don’t change Student just to sort by marks another way — write a Comparator.

Let's take this on the board with one tiny Main class — no extra files. Comparable vs Comparator in Java — sort uses String's natural compare (case-insensitive here). Start from main, go line by line, and stop at each print. That output is the proof for Comparable vs Comparator.

Exam tip

Comparable = natural compareTo. Comparator = extra order without changing the class.

Example

import java.util.*;
public class Main {
  public static void main(String[] args) {
    List<String> names = Arrays.asList("Ravi", "Asha", "Neha");
    names = new ArrayList<>(names);
    names.sort(String::compareToIgnoreCase);
    System.out.println(names);
  }
}

Comparable vs Comparator in Java — sort uses String's natural compare (case-insensitive here).

Short notes

  • DefComparable = compareTo inside the class. Comparator = separate compare.
  • RuleOne natural order. Many extra Comparators.
  • Usesort(list) vs sort(list, comparator).
  • RememberExtra sort → Comparator, don’t edit the class.

Questions

1

Where is compareTo?

2

When Comparator?

Previous← Java ComparatorNextProperties class →
P

GoCareerGo

Utilities · Preparation Hub · Resume · CV · Tools — one workspace.

Workspace

DashboardProfilePreparation HubResume builderCV builderCareer planning

PDF Tools

Merge PDFSplit PDFCompress PDFImage to PDFAll toolsJobs

Image & QR

Compress ImageResize ImageQR ScannerQR GeneratorBlogIT interview prep

Company

FAQFeedbackContactPrivacyTermsSitemap

© 2026 GoCareerGo. Keep moving forward.