Official Definition

From the reference docs of Comparable.compareTo(T):

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. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.)

The implementor must also ensure that the relation is transitive: (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.

Finally, the implementor must ensure that x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.

It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."

In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero or positive.

My Version

In short:

this.compareTo(that)

returns

  • a negative int if this < that
  • 0 if this == that
  • a positive int if this > that

where the implementation of this method determines the actual semantics of < > and == (I don't mean == in the sense of java's object identity operator)

Examples

"abc".compareTo("def")

will yield something smaller than 0 as abc is alphabetically before def.

Integer.valueOf(2).compareTo(Integer.valueOf(1))

will yield something larger than 0 because 2 is larger than 1.

Some additional points

Note: It is good practice for a class that implements Comparable to declare the semantics of it's compareTo() method in the javadocs.

Note: you should read at least one of the following:

  • the Object Ordering section of the Collection Trail in the Sun Java Tutorial
  • Effective Java by Joshua Bloch, especially item 12: Consider implementing Comparable
  • Java Generics and Collections by Maurice Naftalin, Philip Wadler, chapter 3.1: Comparable

Warning: you should never rely on the return values of compareTo being -1, 0 and 1. You should always test for x < 0, x == 0, x > 0, respectively.

Answer from Sean Patrick Floyd on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ ref_string_compareto.asp
Java String compareTo() Method
The comparison is based on the Unicode value of each character in the strings. The method returns 0 if the string is equal to the other string. A value less than 0 is returned if the string is less than the other string (less characters) and ...
Top answer
1 of 7
105

Official Definition

From the reference docs of Comparable.compareTo(T):

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. (This implies that x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception.)

The implementor must also ensure that the relation is transitive: (x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.

Finally, the implementor must ensure that x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.

It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."

In the foregoing description, the notation sgn(expression) designates the mathematical signum function, which is defined to return one of -1, 0, or 1 according to whether the value of expression is negative, zero or positive.

My Version

In short:

this.compareTo(that)

returns

  • a negative int if this < that
  • 0 if this == that
  • a positive int if this > that

where the implementation of this method determines the actual semantics of < > and == (I don't mean == in the sense of java's object identity operator)

Examples

"abc".compareTo("def")

will yield something smaller than 0 as abc is alphabetically before def.

Integer.valueOf(2).compareTo(Integer.valueOf(1))

will yield something larger than 0 because 2 is larger than 1.

Some additional points

Note: It is good practice for a class that implements Comparable to declare the semantics of it's compareTo() method in the javadocs.

Note: you should read at least one of the following:

  • the Object Ordering section of the Collection Trail in the Sun Java Tutorial
  • Effective Java by Joshua Bloch, especially item 12: Consider implementing Comparable
  • Java Generics and Collections by Maurice Naftalin, Philip Wadler, chapter 3.1: Comparable

Warning: you should never rely on the return values of compareTo being -1, 0 and 1. You should always test for x < 0, x == 0, x > 0, respectively.

2 of 7
58

I use this mnemonic :

a.compareTo(b) < 0 // a < b

a.compareTo(b) > 0 // a > b

a.compareTo(b) == 0 // a == b

You keep the signs and always compare the result of compareTo() to 0

People also ask

What is the purpose of the compareTo method in Java?
In Java, the compareTo method serves to compare two objects of identical type and establish their relative sequence, returning a negative integer when the current object is lesser than the compared one, zero if they are equivalent, and a positive integer if the current object exceeds the compared object; effectively establishing the "natural order" for object comparison within a class.
๐ŸŒ
upgrad.com
upgrad.com โ€บ home โ€บ tutorials โ€บ software & tech โ€บ compareto in java
compareTo in Java: A Complete Guide with Practice Exercises
Which classes in Java implement the compareTo method?
In Java, the compareTo method belongs to the Comparable interface, which is implemented by several core Java classes such as String, Integer, Double, and Character. This implementation means these classes possess a built-in compareTo method, enabling natural ordering comparisons among objects of that type.
๐ŸŒ
upgrad.com
upgrad.com โ€บ home โ€บ tutorials โ€บ software & tech โ€บ compareto in java
compareTo in Java: A Complete Guide with Practice Exercises
How does the compareTo method differ from the equals method in Java?
compareTo: Evaluates two strings in lexicographic order. equals: Checks if this string is equal to the given object. CompareTo assesses two strings based on their characters (at matching indices) and returns an integer that can be positive or negative based on the comparison.
๐ŸŒ
upgrad.com
upgrad.com โ€บ home โ€บ tutorials โ€บ software & tech โ€บ compareto in java
compareTo in Java: A Complete Guide with Practice Exercises
๐ŸŒ
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 - compareTo() function in Java is used to compare two strings or objects lexicographically. It returns a positive, zero, or negative integer.
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ java string compareto() method
Java String compareTo() Method with Examples - Scaler Topics
May 10, 2023 - It returns a positive integer if string1 is lexicographically greater than string2, negative if string2 is greater than string1, and zero if both are equal. The compareTo() method in Java throws two Exceptions.
๐ŸŒ
Upgrad
upgrad.com โ€บ home โ€บ tutorials โ€บ software & tech โ€บ compareto in java
compareTo in Java: A Complete Guide with Practice Exercises
March 17, 2025 - In Java, the compareTo method serves ... a negative integer when the current object is lesser than the compared one, zero if they are equivalent, and a positive integer if the current object exceeds the compared object; effectively ...
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ home โ€บ java/lang โ€บ java string compareto method
Java String compareTo Method
September 1, 2008 - The Java String compareTo() method is used to compare two strings lexicographically. It returns an integer value, and the comparison is based on the Unicode value of each character in the strings.
Find elsewhere
๐ŸŒ
Programiz
programiz.com โ€บ java-programming โ€บ library โ€บ string โ€บ compareto
Java String compareTo()
class Main { public static void main(String[] args) { String str1 = "Learn Java"; String str2 = "Learn Java"; String str3 = "Learn Kolin"; int result; // comparing str1 with str2 ยท result = str1.compareTo(str2); System.out.println(result); // 0 // comparing str1 with str3 ยท result = str1.compareTo(str3); System.out.println(result); // -1 // comparing str3 with str1 ยท result = str3.compareTo(str1); System.out.println(result); // 1 } } ... str1 comes before str3 in the dictionary order. Hence, str1.compareTo(str3) returns negative, and str3.compareTo(str1) returns positive.
๐ŸŒ
CodeGym
codegym.cc โ€บ java blog โ€บ strings in java โ€บ java string compareto() method
Java String CompareTo() Method
December 25, 2024 - Always ensure that the parameter is not null. The compareTo() method compares strings based on the Unicode value of each character. It returns 0 if both are lexicographically equal.
๐ŸŒ
Quora
quora.com โ€บ What-does-the-compareto-function-do-in-Java
What does the compareto() function do in Java? - Quora
Each character of both the strings is converted into a Unicode value for comparison. It returns a positive number, negative number or 0 (difference of character value). Following are the three conditions: s1 > s2, it ret...
๐ŸŒ
BeginnersBook
beginnersbook.com โ€บ 2013 โ€บ 12 โ€บ java-string-compareto-method-example
Java String compareTo() Method with examples
The Java String compareTo() method is used for comparing two strings lexicographically. Each character of both the strings is converted into a Unicode value for comparison. If both the strings are equal then this method returns 0 else it returns positive or negative value.
๐ŸŒ
Javatpoint
javatpoint.com โ€บ java-string-compareto
Java String compareTo()
Java String compareTo() method with method signature and examples of concat, compare, touppercase, tolowercase, trim, length, equals, split, string compareto in java etc.
๐ŸŒ
Zero To Mastery
zerotomastery.io โ€บ blog โ€บ java-compareto-method
Beginner's Guide To compareto In Java (With Code Examples) | Zero To Mastery
However, if the words were exactly the same ("Alice".compareTo("Alice")), compareTo would return 0, because thereโ€™s nothing to compare! So the next time you sort a list of names, remember โ€” Java is just running compareTo behind the scenes, checking letters one by one. Speaking of sorting, numbers work in a similar way. Letโ€™s check that out next. Since compareTo sorts Strings alphabetically by checking each letter, you might wonder if it does the same thing for numbers?
๐ŸŒ
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 - 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 as an argument. The natural ordering is defined by the class itself and should be ...
๐ŸŒ
FavTutor
favtutor.com โ€บ blogs โ€บ compareto-method-java
compareTo() method in Java
October 25, 2023 - The compareTo() method returns an integer value that indicates the result of the comparison.
๐ŸŒ
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); }
๐ŸŒ
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. It returns either a positive, negative, or 0.
๐ŸŒ
Software Testing Help
softwaretestinghelp.com โ€บ home โ€บ java โ€บ java string compareto method with programming examples
Java String compareTo Method With Programming Examples
April 1, 2025 - Now, a Java .compareTo() method will provide results based on the ASCII difference in the value of the Lowercase and Uppercase as it will take the character case into consideration.