🌐
W3Schools
w3schools.com › java › ref_string_compareto.asp
Java String compareTo() Method
Access Modifiers Non-Access Modifiers Java Encapsulation Java Packages / API Java Inheritance Java Polymorphism Java super Keyword Java Inner Classes Java Abstraction Java Interface Java Anonymous Java Enum ... Java Data Structures Java Collections Java List Java ArrayList Java LinkedList Java List Sorting Java Set Java HashSet Java TreeSet Java LinkedHashSet Java Map Java HashMap Java TreeMap Java LinkedHashMap Java Iterator Java Algorithms · Java Wrapper Classes Java Generics Java Annotations Java RegEx Java Threads Java Lambda Java Advanced Sorting ... How Tos Add Two Numbers Swap Two Vari
🌐
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

Discussions

comparable - How to implement compareTo method in Java and what does it mean - Stack Overflow
Find centralized, trusted content ... you use most. Learn more about Collectives ... Bring the best of human thought and AI automation together at your work. Explore Stack Internal ... Closed 3 years ago. 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
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
[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
[Java] Never use HashCode to implement compareTo
I can't even begin to understand why hashCode() would ever be considered for this purpose by anyone... Even disregarding your comments about memory addresses, hash collisions for non-equivalent objects are an expectation and should therefore never be used for equality comparisons (returning 0 in your example). More on reddit.com
🌐 r/ProgrammerTIL
13
29
September 23, 2017
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-string-compareto-method-with-examples
Java String compareTo() Method with Examples - GeeksforGeeks
January 20, 2025 - There are three variants of the compareTo() method which are as follows: ... This method compares this String to another Object.
🌐
Programiz
programiz.com › java-programming › library › string › compareto
Java String compareTo()
The compareTo() method takes a single parameter. ... 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
🌐
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
However when we're dealing with things that aren't obviously comparable, like objects and spaceships (in your example), we need to explain to the compiler what criterion is used to say that one spaceship is "bigger" than another. This is where writing a custom (@Override) compareTo method comes in.
🌐
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.
🌐
TechVidvan
techvidvan.com › tutorials › java-string-compareto-method
Java String compareTo() Method with Examples - TechVidvan
March 7, 2024 - public class TechVidvanCompareTo{ public static void main(String args[]) { String a1 = "hello"; String a2 = "hello"; String a3 = "meklo"; String a4 = "hemlo"; System.out.println(a1.compareTo(a2)); System.out.println(a1.compareTo(a3)); System.out.println(a1.compareTo(a4)); } } ... Java allows us to compare Strings based on their content and references. It is used in reference matching (by the == operator), sorting (by the compareTo() method), and authentication (by the equals() method).
🌐
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 lexicographical order, and organizing string lists. Understanding how to ...
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 - Since sorting isn’t just about knowing whether two values are different - but rather how they should be arranged — Java repeatedly calls compareTo to position elements correctly in a list. This allows it to sort objects automatically, without requiring custom logic each time. ... Imagine you’re building a leaderboard for a game. You have a list of players, and you need to rank them based on their scores. The problem? Java doesn’t automatically know how to order them and so you have to define the logic. Here’s how you can use compareTo to sort players by score:
🌐
Scaler
scaler.com › home › topics › java string compareto() method
Java String compareTo() Method with Examples - Scaler Topics
May 10, 2023 - compareTo() in Java takes only a single Object as a parameter which is used for comparison. ... obj1 and obj2 must belong to the same class, and their class must implement the Comparable interface.
🌐
YouTube
youtube.com › codeash
compareto method in java | Java String compareTo() Method Example - YouTube
The Java String class compareTo() method compares the given string with the current string lexicographically. It returns a positive number, negative number, ...
Published   May 16, 2022
Views   10K
🌐
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:
🌐
Quora
quora.com › What-does-the-compareto-function-do-in-Java
What does the compareto() function do in Java? - Quora
Answer (1 of 3): The method compareTo() is used for comparing two strings. 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).
🌐
YouTube
youtube.com › watch
How does compareTo method works internally in Java? - YouTube
In this video, we explain **how the compareTo() method works internally in Java** and how it is used for comparing strings and objects. What you’ll learn: ...
Published   April 18, 2020
🌐
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); }
🌐
BeginnersBook
beginnersbook.com › 2013 › 12 › java-string-compareto-method-example
Java String compareTo() Method with examples
September 16, 2022 - In the above code snippet, the second compareTo() statement returned the length in negative number, this is because we have compared the empty string with str1 while in first compareTo() statement, we have compared str1 with empty string. ... public class JavaExample { public static void main(String args[]) { String str1 = "Cow"; //This is an empty string String str2 = ""; String str3 = "Goat"; int lenOfStr1 = str1.compareTo(str2); int lenOfStr3 = str3.compareTo(str2); System.out.println("Length of string str1: "+lenOfStr1); System.out.println("Length of string str3: "+lenOfStr3); } }
🌐
LabEx
labex.io › tutorials › java-how-to-use-compareto-method-to-compare-java-objects-414156
How to use compareTo() method to compare Java objects | LabEx
Zero if the current object is equal to the argument object · A positive integer if the current object is greater than the argument object · The implementation of the compareTo() method is crucial for the proper ordering of objects in various data structures, such as TreeSet, TreeMap, and sorted collections. It also enables the use of sorting algorithms like Collections.sort() and Arrays.sort() to arrange objects in a specific order.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.lang.string.compareto
String.CompareTo(String) Method (Java.Lang) | Microsoft Learn
In this case, compareTo returns the difference of the lengths of the strings -- that is, the value: <blockquote> this.length()-anotherString.length() </blockquote> For finer-grained String comparison, refer to java.text.Collator. Java documentation for java.lang.String.compareTo(java.lang.String). Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.
🌐
CodeGym
codegym.cc › java blog › strings in java › java string compareto() method
Java String CompareTo() Method
December 25, 2024 - If the compared string is greater lexicographically then the positive value is returned otherwise the negative value is returned. So the Java string compareTo() method is used to compare two strings. The unicode value of each character in the ...
🌐
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...