For performance, it usually best to make the code as simple and clear as possible and this will often perform well (as the JIT will optimise this code best). In your case, the simplest examples are also likely to be the fastest.


I would do either

int cmp = a > b ? +1 : a < b ? -1 : 0;

or a longer version

int cmp;
if (a > b)
   cmp = +1;
else if (a < b)
   cmp = -1;
else
   cmp = 0;

or

int cmp = Integer.compare(a, b); // in Java 7
int cmp = Double.compare(a, b); // before Java 7

It's best not to create an object if you don't need to.

Performance wise, the first is best.

If you know for sure that you won't get an overflow you can use

int cmp = a - b; // if you know there wont be an overflow.

you won't get faster than this.

Answer from Peter Lawrey on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-integer-compareto-method
Java Integer compareTo() method - GeeksforGeeks
April 3, 2023 - The compareTo() method of Integer class of java.lang package compares two Integer objects numerically and returns the value 0 if this Integer is equal to the argument Integer; a value less than 0 if this Integer is numerically less than the ...
Discussions

Is there any difference between Integer.compare(int a, int b) and a == b ?
On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge. If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options: Limiting your involvement with Reddit, or Temporarily refraining from using Reddit Cancelling your subscription of Reddit Premium as a way to voice your protest. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnprogramming
4
1
June 26, 2023
How's the value of compareTo() result derived in java?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnjava
14
8
August 18, 2024
CompareTo error in Java, "error: int cannot be dereferenced"
ints don't have methods, Integers do. Declare Integer value instead of int value. That way value is an object with various methods such as compareTo. More on reddit.com
🌐 r/learnprogramming
4
11
February 21, 2016
[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
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › Integer.html
Integer (Java Platform SE 8 )
October 20, 2025 - NumberFormatException - if the String does not contain a parsable integer. See Also: parseInt(java.lang.String, int) public int compareTo(Integer anotherInteger) Compares two Integer objects numerically. Specified by: compareTo in interface Comparable<Integer> Parameters: anotherInteger - the ...
🌐
TutorialsPoint
tutorialspoint.com › java-integer-compareto-method
Java Integer compareTo() method
September 20, 2019 - The java.lang.Integer.compareTo() method compares two Integer objects numerically. This method returns the value 0 if this Integer is equal to the argument Integer, a value less than 0 if this Integer is numerically less than the argumen
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-integer-compare-method
Java Integer compare() method - GeeksforGeeks
December 5, 2018 - The compare() method of Integer class of java.lang package compares two integer values (x, y) given as a parameter and returns the value zero if (x==y), if (x < y) then it returns a value less than zero and if (x > y) then it returns a value greater than zero...
🌐
BeginnersBook -
beginnersbook.com › home › java › java integer compareto() method
Java Integer compareTo() Method
October 23, 2022 - The compareTo() method compares this Integer with the Integer argument. It returns, 0 if this Integer is equal to given Integer, a value less than 0 if this Integer is less than Integer argument, a value greater than zero if this Integer is greater than Integer argument.
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 - But what if you're working with objects like String or Integer? Unlike numbers, Java doesn't allow direct comparisons using < or > because objects don’t have a built-in way to determine which one is "greater" or "smaller." That’s where compareTocomes in.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.lang.integer.compareto
Integer.CompareTo(Integer) Method (Java.Lang) | Microsoft Learn
Microsoft makes no warranties, express or implied, with respect to the information provided here. Compares two Integer objects numerically. [Android.Runtime.Register("compareTo", "(Ljava/lang/Integer;)I", "")] public int CompareTo(Java.Lang.Integer ...
🌐
LabEx
labex.io › tutorials › java-how-to-display-the-result-of-integer-comparison-in-java-414011
How to display the result of integer comparison in Java | LabEx
In this example, the compareTo() method is used to compare the values of a and b, and the result is used to determine the relationship between the two integers. By understanding these different ways to compare integers and display the results, ...
🌐
Reddit
reddit.com › r/learnjava › how's the value of compareto() result derived in java?
r/learnjava on Reddit: How's the value of compareTo() result derived in java?
August 18, 2024 -

The compareTo method returns three types of results:

  • A negative integer if the first string comes before the second string in lexicographical order.

  • Zero if the two strings are equal.

  • A positive integer if the first string comes after the second string in lexicographical order.

Note that it says positive/negative integer and not +1 or -1. How's the value of such integer derived?

I converted

String s1 = "Welcome to Java";
String s2 = "Programming is fun";
s1.compareTo(s2);

And I'm getting -7 as result from the java compiler. However, I don't understand how is this result coming?

I calculated the ASCII values of these strings.

s1=87 101 108 99 111 109 101 116 111 74 97 118 97

s2=80 114 111 103 114 97 109 105 110 103 105 115 102 117 110

It's not the net s1-s2 of ascii values, because that'd be a very large value.

Now, if I calculate +1 if s1>s2 and -1 if s1<s2, then I'd still not get -7.

Can anyone guide me?

References:

https://stackoverflow.com/questions/48041889/when-using-compareto-for-strings-returns-10-all-the-time

It seems like the returned value is implementation specific, thus I want to know say the oldest version of java's implementation.

🌐
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
🌐
Oracle
docs.oracle.com › en › java › javase › 21 › docs › api › java.base › java › lang › Integer.html
Integer (Java SE 21 & JDK 21)
January 20, 2026 - NumberFormatException - if the String does not contain a parsable integer. See Also: parseInt(java.lang.String, int) public int compareTo · (Integer anotherInteger) Compares two Integer objects numerically. Specified by: compareTo in interface Comparable<Integer> Parameters: anotherInteger ...
🌐
Study.com
study.com › business courses › business 104: information systems and computer applications
How to Compare Integer Values in Java - Lesson | Study.com
July 2, 2025 - In Java, you can compare integer values by using methods available in a wrapper class, that is the parent class of the data type (Integer). Integer (capital I) is a class unto itself, and is a wrapper class for int data types, as Double would be for double. Thus, Integer has its own methods. One of the methods available is the compareTo() method, which compares two Inteer values and returns the following values:
🌐
TutorialsPoint
tutorialspoint.com › java-integer-compare-method
Java Integer compare() method
January 6, 2025 - The Integer.compare() method is a simple and effective way to compare integers in Java. It is especially useful in sorting and when working with collections.
🌐
Java Guides
javaguides.net › 2024 › 06 › java-integer-compareto-method.html
Java Integer compareTo() Method
June 17, 2024 - The Integer.compareTo() method is an instance method in the Integer class in Java. It compares two Integer objects and returns an integer indicating their relative order.
🌐
Monicagranbois
monicagranbois.com › blog › java › comparing-integers-using-integercompare-vs-subtraction
Comparing integers using Integer.compare vs subtraction
August 4, 2015 - Overflow, that’s why! When comparing numbers of extreme magnitude, such as MAX_VALUE and -1, these are subtracted, giving a result with the wrong sign. That’s why the sorting fails in the case. The correct way to compare integers is, as you note, using Integer.compare():
🌐
Baeldung
baeldung.com › home › java › core java › guide to implementing the compareto method
Guide to Implementing the compareTo Method - Java
May 29, 2025 - The compareTo method compares the current object with the object sent as a parameter. When implementing it, we need to make sure that the method returns: A positive integer, if the current object is greater than the parameter object
🌐
IncludeHelp
includehelp.com › java › integer-class-compareto-method-with-example.aspx
Java - Integer Class compareTo() Method
compareTo() method does not throw an exception at the time of comparing the Integer object. ... Integer value2 – represents the Integer object to compare with. The return type of this method is int, it returns an integer value. It returns 0 if value1 is mathematically equal to value2.
🌐
Studytonight
studytonight.com › java-wrapper-class › java-integer-compareto-method
Java Integer compareTo() Method - Studytonight
January 15, 2021 - import java.util.Scanner; import java.lang.Integer; public class StudyTonight { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter first and second number "); try { Integer n1 = sc.nextInt(); Integer n2 = sc.nextInt(); int r = n1.compareTo(n2); if(r > 0) { System.out.println("first number is greater"); } else if(r< 0) { System.out.println("second number is greater"); } else { System.out.println("both numbers are equal"); } } catch(Exception e) { System.out.println("Error!!"); } } }