This is the right way to compare strings:

int studentCompare = this.lastName.compareTo(s.getLastName()); 

This won't even compile:

if (this.getLastName() < s.getLastName())

Use if (this.getLastName().compareTo(s.getLastName()) < 0) instead.

So to compare fist/last name order you need:

int d = getFirstName().compareTo(s.getFirstName());
if (d == 0)
    d = getLastName().compareTo(s.getLastName());
return d;
Answer from Eugene Retunsky on Stack Overflow
Top answer
1 of 9
24

This is the right way to compare strings:

int studentCompare = this.lastName.compareTo(s.getLastName()); 

This won't even compile:

if (this.getLastName() < s.getLastName())

Use if (this.getLastName().compareTo(s.getLastName()) < 0) instead.

So to compare fist/last name order you need:

int d = getFirstName().compareTo(s.getFirstName());
if (d == 0)
    d = getLastName().compareTo(s.getLastName());
return d;
2 of 9
18

The compareTo method is described as follows:

Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

Let's say we would like to compare Jedis by their age:

class Jedi implements Comparable<Jedi> {

    private final String name;
    private final int age;
        //...
}

Then if our Jedi is older than the provided one, you must return a positive, if they are the same age, you return 0, and if our Jedi is younger you return a negative.

public int compareTo(Jedi jedi){
    return this.age > jedi.age ? 1 : this.age < jedi.age ? -1 : 0;
}

By implementing the compareTo method (coming from the Comparable interface) your are defining what is called a natural order. All sorting methods in JDK will use this ordering by default.

There are ocassions in which you may want to base your comparision in other objects, and not on a primitive type. For instance, copare Jedis based on their names. In this case, if the objects being compared already implement Comparable then you can do the comparison using its compareTo method.

public int compareTo(Jedi jedi){
    return this.name.compareTo(jedi.getName());
}

It would be simpler in this case.

Now, if you inted to use both name and age as the comparison criteria then you have to decide your oder of comparison, what has precedence. For instance, if two Jedis are named the same, then you can use their age to decide which goes first and which goes second.

public int compareTo(Jedi jedi){
    int result = this.name.compareTo(jedi.getName());
    if(result == 0){
        result = this.age > jedi.age ? 1 : this.age < jedi.age ? -1 : 0;
    }
    return result;
}

If you had an array of Jedis

Jedi[] jediAcademy = {new Jedi("Obiwan",80), new Jedi("Anakin", 30), ..}

All you have to do is to ask to the class java.util.Arrays to use its sort method.

Arrays.sort(jediAcademy);

This Arrays.sort method will use your compareTo method to sort the objects one by one.

🌐
Baeldung
baeldung.com › home › java › core java › guide to implementing the compareto method
Guide to Implementing the compareTo Method - Java
May 29, 2025 - TreeMap and TreeSet are two implementations from the Java Collections Framework that assist us with the automatic sorting of their elements. We may use objects that implement the Comparable interface in a sorted map or as elements in a sorted set. Let’s look at an example of a custom class that compares players based on the number of goals they have scored: @Override public int compareTo(FootballPlayer anotherPlayer) { return Integer.compare(this.goalsScored, anotherPlayer.goalsScored); }
Discussions

compareTo(Object o) method problem
Have you added implements Comparable to your class declaration? e.g.: public class Process implements Comparable { More on reddit.com
🌐 r/javahelp
7
1
November 11, 2018
Java CompareTo Sorting - Sorting Multiple Fields for Same Object
Joseph Wagner is having issues with: I have an ArrayList of objects - Player, and I currently have the code to sort by its field, last name. Player has an additional field, height, ... More on teamtreehouse.com
🌐 teamtreehouse.com
1
September 14, 2017
Can somebody help me with java (compareto()???)
A few thoughts: compareTo does not return -1, 0, 1. compareTo only guarantees that it returns either a negative, zero, or positive number. It would be incorrect to write code that compares the output of a call to compareTo against -1 or 1. e.g. if (a.compareTo(b) == -1) // wrong if (a.compareTo(b) < 0) // right CompareTo is used to establish the idea that one object can be greater than, equal to, or less than another object. For instance, Integers are Comparable, and they have a compareTo method. One Integer is larger than another if the int value it contains is larger (numerically) than the other. Strings are Comparable. Doubles are Comparable. As you noted, many other things can be Comparable, such as Students. Java chose to compare Strings lexicographically. This is similar to how a real-life dictionary would sort words in the English alphabet. Essentially, Strings are sorted the same way they would be sorted in the dictionary, and we use the ASCII table as the alphabet (instead of a regular 26-letter alphabet). This implies that capital letters come before lower-case letters. (e.g. "Z" < "a") The ternary operator is ? :. The syntax is: b ? x : y Where b is a boolean expression. x and y are expressions. If b is true, then the ternary operator returns x. Otherwise, it returns y. For instance, rather than writing: int x = 3; // or whatever other value you want if (x < 5) System.out.println("x is less than 5"); else System.out.println("x is greater than or equal to 5"); You can instead write: int x = 3; // or whatever other value you want System.out.println(x < 5 ? "x is less than 5" : "x is greater than or equal to 5"); More on reddit.com
🌐 r/learnprogramming
5
6
January 20, 2013
[Java] Need help with a Generic compareTo
public class Sorter> { ... public int compareTo(T other) { if(this.compareTo(other) > 0) return 1; else if(this.compareTo(other) == 0) return 0; else return -1; } } I'm not sure I understand what you're trying to do with your compareTo() method. You're attempting to compare a Sorter object with a T object? That is not a logical comparison. I'm not sure why you even need this method. In your sortIds(List, List) method, you're correctly using the compareTo() method of the Comparable objects. === Also in lines 17-19, do I need to have the cast there, or is there another way around it? The casts that you're performing in your constructor are not safe. There is no way of knowing that the object at temp[0] is actually of type T. For example, if you created a new Sorter(scanner), the code in your constructor would obviously not be correct, since temp is an array of Strings, and you'd be casting them to Integer. It the constructor may run without error, due to the type-erasured nature of generics, but you'll eventually run into problems when you think you have a List, but it is actually List, for example. I don't even think that code should be part of the constructor. You should read the input in a separate method, (such as your main() method), where you can convert the input to the appropriate Comparable types (e.g. parsing an integer from the String input), and then pass your type-safe IDs to your Sorter class. More on reddit.com
🌐 r/learnprogramming
2
1
January 20, 2013
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › Comparable.html
Comparable (Java Platform SE 8 )
October 20, 2025 - Objects that implement this interface can be used as keys in a sorted map or as elements in a sorted set, without the need to specify a comparator. The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2) for every e1 and e2 of class C.
🌐
Medium
medium.com › @dr4wone › equals-vs-compareto-in-java-understanding-the-differences-fce0a0d4b292
Equals vs. compareTo in Java: Understanding the Differences | by Daniel Baumann | Medium
April 9, 2023 - The compareTo method is used for ordering objects of a class, and it should return a negative integer, zero, or a positive integer depending on whether the object being compared is less than, equal to, or greater than the object passed as an ...
🌐
W3Schools
w3schools.com › java › ref_string_compareto.asp
Java String compareTo() Method
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Server Java Syllabus Java Study Plan Java Interview Q&A Java Certificate ... String myStr1 = "Hello"; String myStr2 = "Hello"; System.out.println(myStr1.compareTo(myStr2)); // Returns 0 because they are equal
🌐
Reddit
reddit.com › r/javahelp › compareto(object o) method problem
r/javahelp on Reddit: compareTo(Object o) method problem
November 11, 2018 -

I need my class to implement the Comparable interface, but I can't get the compareTo() method to work. The error I'm getting is "The method compareTo(Process) of type Process must override or implement a supertype method"

The class creates Process objects.

@Override
public int compareTo(Process p2) {
	
	return this.getPriority() - p2.getPriority();
}

Obviously if I remove the @Override it works, but then I have an error that I need to add unimplemented methods. How do you fix this? I tried casting the Process as an Object but that didn't work.

🌐
Team Treehouse
teamtreehouse.com › community › java-compareto-sorting-sorting-multiple-fields-for-same-object
Java CompareTo Sorting - Sorting Multiple Fields for Same Object (Example) | Treehouse Community
September 14, 2017 - public class Player implements Comparable<Player> @Override public int compareTo(Player object) { Player other = (Player) object; // We always want to sort by last name then first name if(equals(other)) { return 0; } return lastName.compareTo(other.lastName); } Collections.sort(team.getPlayerList()); Android Development Techdegree Graduate 27,137 Points ... I figured this out, I needed to utilize comparators. Here is a good resource: https://beginnersbook.com/2013/12/java-arraylist-of-object-sort-example-comparable-and-comparator/
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › java › comparable-interface-in-java-with-examples
Java Comparable Interface - GeeksforGeeks
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.
Published   1 month ago
🌐
Zero To Mastery
zerotomastery.io › blog › java-compareto-method
Beginner's Guide To compareto In Java (With Code Examples) | Zero To Mastery
March 3, 2025 - Since sorting isn’t just about knowing whether two values are different - but rather how they should be arranged — Java repeatedly calls compareTo to position elements correctly in a list. This allows it to sort objects automatically, without requiring custom logic each time.
🌐
HappyCoders.eu
happycoders.eu › java › comparator-comparable-compareto
compareTo, Comparable, Comparator - Comparing Objects in Java
June 12, 2025 - The compareTo() method is used behind the scenes to sort an array or list of objects, for example as follows: public class NameSortExample { public static void main(String[] args) { String[] names = {"Mary", "James", "Patricia", "John", "Jennifer", ...
🌐
Reddit
reddit.com › r/learnprogramming › can somebody help me with java (compareto()???)
r/learnprogramming on Reddit: Can somebody help me with java (compareto()???)
January 20, 2013 -
  • I have a vague idea of what it does. It returns -1,0,1 depending on the circumstances.

  • But this is what I don't get. If you're comparing strings, how does it behave? I'm not even sure how the code looks like.. It doesn't make sense to compare strings.

  • How does the ordering work for this function if you're comparing a string? Is it the length of the string?

  • I just don't understand it.

  • Also taking a look at the following website and scrolling down:

http://javarevisited.blogspot.ca/2011/11/how-to-override-compareto-method-in.html

  • we see a "Student" class. Specifically paying attention to :

  • "return (this.id < otherStudent.id ) ? -1: (this.id > otherStudent.id) ? 1:0"

  • What are the following strings of symbols trying to say? I don't understand any of it =/. Can somebody break it down? Where did the ? -1: come from and what does it mean?

  • Same with the ? 1:0

  • Also if we look at the same page, you'll see another class below the "Student" class.

  • This time, it's the same student class but implements comparable<student>. Why does the compareTo() Method return the following value? "return age - otherStudent.age;"

Top answer
1 of 3
4
A few thoughts: compareTo does not return -1, 0, 1. compareTo only guarantees that it returns either a negative, zero, or positive number. It would be incorrect to write code that compares the output of a call to compareTo against -1 or 1. e.g. if (a.compareTo(b) == -1) // wrong if (a.compareTo(b) < 0) // right CompareTo is used to establish the idea that one object can be greater than, equal to, or less than another object. For instance, Integers are Comparable, and they have a compareTo method. One Integer is larger than another if the int value it contains is larger (numerically) than the other. Strings are Comparable. Doubles are Comparable. As you noted, many other things can be Comparable, such as Students. Java chose to compare Strings lexicographically. This is similar to how a real-life dictionary would sort words in the English alphabet. Essentially, Strings are sorted the same way they would be sorted in the dictionary, and we use the ASCII table as the alphabet (instead of a regular 26-letter alphabet). This implies that capital letters come before lower-case letters. (e.g. "Z" < "a") The ternary operator is ? :. The syntax is: b ? x : y Where b is a boolean expression. x and y are expressions. If b is true, then the ternary operator returns x. Otherwise, it returns y. For instance, rather than writing: int x = 3; // or whatever other value you want if (x < 5) System.out.println("x is less than 5"); else System.out.println("x is greater than or equal to 5"); You can instead write: int x = 3; // or whatever other value you want System.out.println(x < 5 ? "x is less than 5" : "x is greater than or equal to 5");
2 of 3
2
Thank you lightcloud5 and TinyLebowski. This clears up most mysteries I'm having. I still don't quite understand how instances of classes can be compared though. Is this how it works? We Override the compareTo() method and write our own. Then we specifically tell how to compare using what we think is appropriate. So in the end, we can compare with either int, double, float, string, etc. We just have to define how to compare things right?
🌐
Tutorialspoint
tutorialspoint.com › java › number_compareto.htm
Java - compareTo() Method
Java Vs. C++ ... The method compares the Number object that invoked the method to the argument. It is possible to compare Byte, Long, Integer, etc. However, two different types cannot be compared, both the argument and the Number object invoking the method should be of the same type. public ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-string-compareto-method-with-examples
Java String compareTo() Method with Examples - GeeksforGeeks
January 20, 2025 - compareTo() function in Java is used to compare two strings or objects lexicographically. It returns a positive, zero, or negative integer.
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › compareto in java
compareTo in Java: A Complete Guide with Practice Exercises
March 17, 2025 - Learn how to use the compareTo() in Java for string and object comparison. Understand syntax, examples, return values, common interview questions and practice exercises.
🌐
Jenkov
jenkov.com › tutorials › java-collections › comparable.html
Java Comparable
October 4, 2020 - Notice how there is no type parameter specified after the "implements Comparable" interface in the class declaration. Notice also, how the parameter type of the compareTo() object is no longer Spaceship, but Object.
🌐
LabEx
labex.io › tutorials › java-how-to-use-compareto-method-to-compare-java-objects-414156
How to use compareTo() method to compare Java objects | LabEx
The compareTo() method is a fundamental part of the Java programming language. It is used to compare two objects of the same class and determine their relative order.
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-override-compareto-method-in-java
How to Override compareTo() Method in Java? - GeeksforGeeks
July 23, 2025 - The comparable interface provides a compareTo() method to sort the elements. To summarize, in Java, if sorting of objects needs to be based on natural order then use the compareTo() method of Comparable Interface.
🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › java.base › java › lang › Comparable.html
Comparable (Java SE 11 & JDK 11 )
January 20, 2026 - Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y.
🌐
Coderanch
coderanch.com › t › 532247 › java › compareTo-method
compareTo method (Beginning Java forum at Coderanch)
March 27, 2011 - But either way, this compareTo method is basically just comparing the frequency value of the current object to the frequency value of the other object. It does this by converting the frequency int values to Integer instances, so it's comparing (Integer)frequency to (Integer)d.frequency.
🌐
Quora
quora.com › How-do-I-use-the-compareTo-method-in-Java
How to use the compareTo() method in Java - Quora
Answer (1 of 18): The compareTo() method is already implemented in Java for the types String, Double, java.io.File, java.util.Date, Integer, as these types have implemented the Comparable interface. Let's understand with an example on how we would use this method for these types. Below is the p...