The general contract of Comparable.compareTo(o) is to return

  • a positive integer if this is greater than the other object.
  • a negative integer if this is lower than the other object.
  • 0 if this is equals to the other object.

In your example "ab2".compareTo("ac3") == -1 and "ab2".compareTo("ab3") == -1 only means that "ab2" is lower than both "ac3" and "ab3". You cannot conclude anything regarding "ac3" and "ab3" with only these examples.

This result is expected since b comes before c in the alphabet (so "ab2" < "ac3") and 2 comes before 3 (so "ab2" < "ab3"): Java sorts Strings lexicographically.

Answer from Tunaki 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 ...
🌐
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. It compares strings based on the Unicode value of each character in the strings.
Discussions

java - How does compareTo work? - Stack Overflow
This result is expected since b ... "ab3"): Java sorts Strings lexicographically. ... Sign up to request clarification or add additional context in comments. ... It is important to know that "ab7" would still be smaller than "ac2" even though the last integer suggests ab7 should be greater than ac2 because the compareTo() lexicographically works as follows:- ... More on stackoverflow.com
🌐 stackoverflow.com
[deleted by user]
However what determines ascending or descending order then? a.compareTo(b) versus b.compareTo(a). That's all there's to it really. The compare function is used by the sorting algorithm to decide which of the two is 'bigger'. If you reverse the comparison you also reverse the order. Another option is to simply reverse a list sorted in ascending order to get it in descending order :) Okay we get -1, or 1, or 0 but what determines if it should descend or ascend? The 'larger' of the two will always be put after the smaller of the two. If you want to reverse the order, you need to basically just swap the output. Simple example: var list = List.of(1, 4, 8, 2, 10, 6); var ascending = list.stream().sorted((a, b) -> Integer.compare(a, b)).toList(); System.out.println(ascending); var descending = list.stream().sorted((a, b) -> Integer.compare(b, a)).toList(); System.out.println(descending); See how the only difference is the order in which I pass the integers to Integer.compare? That's really all there's to it. How the actual sorting works; I suggest following a tutorial yourself where you implement a few sorting algorithms yourself. That will also make it very clear how the output of a comparison is used for sorting. More on reddit.com
🌐 r/learnprogramming
12
1
December 31, 2021
How does compareTo work?
You're getting answers all over the place here, but I don't really feel that they addressed what you are actually asking. The compareTo() function is part of the Comparable interface. Interfaces are like contracts. They are not classes but instead are promises that the class implementing them supports some functionality (the compareTo() method in our case). So lets take a look at the actual Comparable interface: 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 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. This is the contract of the Comparable interface and I've highlighted the part that concerns us. So in our case, String is an Object implementing the Comparable interface and thus it has already defined the compareTo function. It so happens that using compareTo to sort Strings will return them in canonical (i.e. alphabetical order) but the way a given object is sorted (or compared) is entirely up to the programmer writing that class. The comment below mine has the source actually used for java.lang.String's compareTo() if you are curious. I would also suggest trying to create your own simple class that implements the Comparable interface. For instance, you could try writing a myInteger class which implements Comparable and in your compareTo() function you would write a snippet of code that compares your int with another int. Note: in practice, all of the primitive wrapper classes (e.g. Integer, Double, etc.) already implement Comparable. T And finally, I just have to say that the real magic of implementing the Comparable interface is that you can give it to other methods that will automatically sort your object according to how you have defined compareTo. So to take Strings for an example: if you have an unsorted collection of Strings, you can pass it as an argument to Collections.sort() and it will return a sorted collection. If you take the time to write out that myInteger class, you can also pass a collection of myInteger's to Collections.sort() and it will automatically sort them. More on reddit.com
🌐 r/javahelp
3
2
July 19, 2016
Understanding the compareTo() method
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. The result is positive if the first string is lexicographically greater than the second string else the result would be negative. More on reddit.com
🌐 r/javahelp
16
15
August 8, 2020
🌐
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

🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › Comparable.html
Comparable (Java Platform SE 8 )
October 20, 2025 - For example, if one adds two keys a and b such that (!a.equals(b) && a.compareTo(b) == 0) to a sorted set that does not use an explicit comparator, the second add operation returns false (and the size of the sorted set does not increase) because a and b are equivalent from the sorted set's perspective. Virtually all Java core classes that implement Comparable have natural orderings that are consistent with equals.
🌐
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 - 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 - 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 ...
Find elsewhere
🌐
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.
🌐
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).
🌐
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.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › system.string.compareto
String.CompareTo Method (System) | Microsoft Learn
Compares this instance with a specified object or String and returns an integer that indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified object or String. Both overloads of the CompareTo method perform culture-sensitive and case-sensitive comparison.
🌐
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 ...
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › compareto in java
compareTo in Java: A Complete Guide with Practice Exercises
March 17, 2025 - Build Tools (Optional): Get to know tools such as Maven or Gradle for managing projects, particularly if your project will involve various dependencies. ... The method compareTo() evaluates two strings in a lexicographical manner.
🌐
Medium
medium.com › @AlexanderObregon › javas-compareto-and-clone-explained-32acb444e6b2
Understanding compareTo() and clone() in Java | Medium
July 10, 2024 - The compareTo() method is a vital part of the Comparable interface in Java, designed to allow objects of a class to be compared to each other. This is especially useful for sorting collections of objects.
🌐
Igor's Techno Club
igorstechnoclub.com › java-compareto
Java Comparable compareTo method: Natural Order Of Things | Igor's Techno Club
July 22, 2024 - By implementing the Comparable interface and overriding compareTo, you can define custom ordering for your classes, enabling them to be easily sorted and compared. Whether you're working with Java's built-in ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-compare-method-works-in-java
How compare() method works in Java - GeeksforGeeks
July 11, 2025 - public int compare(Object obj1, Object obj2) { Integer I1 = (Integer)obj1; // typecasting object type into integer type Integer I2 = (Integer)obj2; // same as above .. // 1. return I1.compareTo(I2); // ascending order [0, 5, 10, 15, 20] // 2. return -I1.compareTo(I2); // descending order [20, 15, 10, 5, 0] // 3.
🌐
Software Testing Help
softwaretestinghelp.com › home › java › java string compareto method with programming examples
Java String compareTo Method With Programming Examples
April 1, 2025 - Let’s understand these three variants in detail with the help of an example. Here is an example of compareTo() Java method. The comparison is based on the difference in the ASCII value of the characters.
🌐
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...
🌐
Codecademy
codecademy.com › docs › java › date › .compareto()
Java | Date | .compareTo() | Codecademy
July 27, 2023 - System.out.println("Comparing firstDate and nullDate: " + firstDate.compareTo(nullDate)); } } Copy to clipboard · Copy to clipboard · The output will be: Comparing firstDate and secondDate: -1 · Comparing firstDate and thirdDate: 0 · Comparing firstDate and fourthDate: 1 · Exception in thread "main" java.lang.NullPointerException ·
🌐
BeginnersBook
beginnersbook.com › 2013 › 12 › java-string-compareto-method-example
Java String compareTo() Method with examples
September 16, 2022 - 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.