🌐
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 ...
🌐
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.
🌐
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.
Find elsewhere
🌐
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 - This method returns an integer whose sign is that of calling compareTo with normalized versions of the strings where case differences have been eliminated by calling Character.toLowerCase(Character.toUpperCase(character)) on each character. Note that this method does not take locale into account, and will result in an unsatisfactory ordering for certain locales. The java.text package provides collators to allow locale-sensitive ordering.
🌐
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 ...