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
🌐
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

🌐
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.
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
🌐
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.
🌐
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); }
🌐
Zero To Mastery
zerotomastery.io › blog › java-compareto-method
Beginner's Guide To compareto In Java (With Code Examples) | Zero To Mastery
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?
🌐
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
Find elsewhere
🌐
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 ...
🌐
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.
🌐
Programiz
programiz.com › java-programming › library › string › compareto
Java String compareTo()
The compareTo() method takes the letter case (uppercase and lowercase) into consideration. class Main { public static void main(String[] args) { String str1 = "Learn Java"; String str2 = "learn Java"; int result; // comparing str1 with str2
🌐
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.
🌐
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.
🌐
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.
🌐
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
Anyway, this code uses String.compareTo() implementation, if spaceshipClass comparison is not 0, then return the result, otherwise compare registrationNo and return result. If you want to understand how to use compareTo() it would be best to ...
🌐
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.
🌐
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 - Java provides two methods for comparing objects: equals() and compareTo(). Both methods are used to compare objects, but they have…
🌐
Blogger
javarevisited.blogspot.com › 2011 › 11 › how-to-override-compareto-method-in.html
How to override compareTo method in Java - Example Tutorial
How does it affect BigDecimal ? well if you store these two BigDecimal in HashSet you will end up with duplicates (violation of Set Contract) i.e. two elements while if you store them in TreeSet you will end up with just 1 element because HashSet uses equals to check duplicates while TreeSet uses compareTo to check duplicates. That's why its suggested to keep compareTo consistent with equals method in java.
🌐
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.
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › lang › Comparable.html
Comparable (Java Platform SE 7 )
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.
🌐
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...