Java Comparable & Comparator Quiz

This Java quiz covers sorting objects. You will read compareTo() results, build comparators with Comparator.comparing(), reversed() and thenComparing(), and find out what happens when a class has no natural order or a TreeSet thinks two values are equal.

Medium 10 questions ~6 minutes Pass at 80% Java 17

Choose a mode

Playing as a guest: sign in to keep your XP and streak.

Sample question

Question 1 of 10

a.compareTo(b) returns a negative number. What does that mean?

Show the answer

D. a comes before b compareTo() returns a negative number if a sorts before b, zero if they are equal and a positive number if a sorts after. Only the sign matters, not the exact value.

What this quiz covers

  • What compareTo() returns and what it means
  • Implementing Comparable for natural order
  • Comparator.comparing(), reversed(), thenComparing()
  • Sorting objects that are not Comparable
  • The a - b comparator bug and TreeSet duplicates

Questions people ask

Do I need an account?

No. Anyone can play. Sign in to keep your XP, streak, badges and history.

Can I retake it?

Yes. Your best score is kept, and the questions and answers are shuffled each time.