🌐
W3Schools
w3schools.com › java › ref_string_compareto.asp
Java String compareTo() Method
The compareTo() method compares two strings lexicographically.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › Comparable.html
Comparable (Java Platform SE 8 )
October 20, 2025 - This interface is a member of the Java Collections Framework. Since: 1.2 · See Also: Comparator · int compareTo(T o) 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 ...
Discussions

comparable - How to implement compareTo method in Java and what does it mean - Stack Overflow
I'm very new to java. I know that the Java Comparable interface has only one method, which has an int return type. However, I'm not sure what I am actually doing when I want to override the compareTo More on stackoverflow.com
🌐 stackoverflow.com
java - How do I write a compareTo method which compares objects? - Stack Overflow
I am learning about arrays, and basically I have an array that collects a last name, first name, and score. I need to write a compareTo method that will compare the last name and then the first na... More on stackoverflow.com
🌐 stackoverflow.com
comparison - Tricky compareTo, inheritance, easy to extend - Java - Software Engineering Stack Exchange
Let's say we have 4 classes A, B, C, D where: A is a superclass of both B and C and C is a superclass of D. I suppose, in a diagram, it should look like this: A / \ B C \ D More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
April 3, 2013
When to use compareTo() and compare()?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
13
2
January 15, 2024
🌐
Reddit
reddit.com › r/javahelp › understanding the compareto() method
r/javahelp on Reddit: Understanding the compareTo() method
August 8, 2020 -

From what I have been reading, the compareTo() method returns the difference of the Unicode numerical values of two Strings when they are compared with each other. For instance, the String "hello" when compared with the String "hello" returns an integer value of zero, since they both have exactly the same Unicode characters in them. Based on my understanding of this method, "hello" should return zero when compared to "olleh", because the two Strings have the exact same Unicode characters in them. Instead, though, I am getting integer value of 7 returned to the console. Can someone break this down a bit for me to help me understand it better? Thanks in advance. Here is my code:

String str1 = "hello";
String str2 = "olleh";
System.out.println(str1.compareTo(str2)); // 7

🌐
GeeksforGeeks
geeksforgeeks.org › java › java-string-compareto-method-with-examples
Java String compareTo() Method with Examples - GeeksforGeeks
January 20, 2025 - The Java compareTo() method compares the given string with the current string lexicographically. It returns a positive number, a negative number, or 0.
🌐
Stack Overflow
stackoverflow.com › questions › 72160928 › how-to-implement-compareto-method-in-java-and-what-does-it-mean
comparable - How to implement compareTo method in Java and what does it mean - Stack Overflow
This is where writing a custom (@Override) compareTo method comes in. By default the compareTo method returns either 1, 0 or -1. There is no inherent meaning to these numbers, in fact they can be any numbers you like (as long as they are different).
🌐
CodeGym
codegym.cc › java blog › strings in java › java string compareto() method
Java String CompareTo() Method
December 25, 2024 - The java string class compareTo() method returns the 0 value if both strings are lexicographically equal. If the compared string is greater lexicographically then the positive value is returned otherwise the negative value is returned.
🌐
Codecademy
codecademy.com › docs › java › strings › .compareto()
Java | Strings | .compareTo() | Codecademy
July 14, 2025 - The .compareTo() method is a built-in Java method compares two strings lexicographically by evaluating the Unicode value of each character.
Find elsewhere
🌐
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 - It’s Java’s built-in method for comparing objects, helping you sort lists, rank values, and organize data the way you want. But if you’ve never used it before, it might seem a little weird. Why does it return -1, 0, or 1 instead of true or false? Don’t worry because we’ll cover all that and more, so that by the end of this guide, you’ll not only understand how compareTo works - you’ll be confident using it to compare strings, numbers, and even custom objects.
🌐
Scaler
scaler.com › home › topics › java string compareto() method
Java String compareTo() Method with Examples - Scaler Topics
May 10, 2023 - Thus, using the compareTo() in Java we can find the length of the string by comparing with an empty string as it returns the length of the non-empty string with positive and negative signs as per the position of the non-empty string.
🌐
Jenkov
jenkov.com › tutorials › java-collections › comparable.html
Java Comparable
October 4, 2020 - The Java Comparable interface is used to make your classes comparable, so they can be automatically sorted using Java's built-in sorting functionality.
🌐
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 to compare objects based on their natural ordering. It returns a negative integer, zero, or a positive integer, depending on whether the current object is less than, equal to, or greater than the object passed ...
🌐
TechVidvan
techvidvan.com › tutorials › java-string-compareto-method
Java String compareTo() Method with Examples - TechVidvan
March 7, 2024 - The compareTo() function of the Java String class lexicographically compares the inputted string with the currently displayed string.
🌐
Programiz
programiz.com › java-programming › library › string › compareto
Java String compareTo()
Become a certified Java programmer. Try Programiz PRO! ... The compareTo() method compares two strings lexicographically (in the dictionary order).
🌐
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...
🌐
Coderanch
coderanch.com › t › 406204 › java › declare-compareTo-method-invoke-main
How to declare compareTo() method and invoke it from the main method? (Beginning Java forum at Coderanch)
February 18, 2007 - First off, if you are going to write a compareTo() method in your class, then you may as well declare to the world that instances of your class can now be used wherever a Comparable<State> is expected. You do that by declaring that your class implements Comparable<State> Now, as far as implementing a useful compareTo() method for your class, primitives (int, double, etc.) have no methods.
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.

🌐
Codecademy
codecademy.com › docs › java › date › .compareto()
Java | Date | .compareTo() | Codecademy
July 27, 2023 - The following example shows the implementation of Date.compareTo(): import java.util.Date; public class Main { public static void main(String[] args) { Date firstDate = new Date(2023, 1, 18); Date secondDate = new Date(2023, 1, 19); Date thirdDate = new Date(2023, 1, 18); Date fourthDate = new Date(2023, 1, 17); Date nullDate = null; System.out.println("Comparing firstDate and secondDate: " + firstDate.compareTo(secondDate)); System.out.println("Comparing firstDate and thirdDate: " + firstDate.compareTo(thirdDate)); System.out.println("Comparing firstDate and fourthDate: " + firstDate.compareTo(fourthDate)); System.out.println("Comparing firstDate and nullDate: " + firstDate.compareTo(nullDate)); } } Copy to clipboard ·
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › String.html
String (Java Platform SE 8 )
October 20, 2025 - If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two string -- that is, the value:
🌐
Vultr Docs
docs.vultr.com › java › standard-library › java › lang › String › compareTo
Java String compareTo() - Compare Strings Alphabetically | Vultr Docs
May 15, 2025 - The compareTo() method in Java is a crucial function from the String class that facilitates the alphabetical comparison of two strings. This method is commonly used in Java string comparison, especially for sorting strings, determining ...