VOOZH about

URL: https://www.geeksforgeeks.org/java/java-integer-compareto-method/

⇱ Java Integer compareTo() method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java Integer compareTo() method

Last Updated : 3 Apr, 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 argument Integer; and a value greater than 0 if this Integer is numerically greater than the argument Integer (signed comparison). 

Syntax :

public int compareTo(Integer anotherInt)
Parameter :
anotherInt- : the Integer to be compared.
Return :
- 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 argument Integer; 
- and a value greater than 0 if this Integer is
numerically greater than the argument Integer
(signed comparison).

Example 01 : To show working of java.lang.Integer.compareTo() method. 

Output:

-1
0
1

Example 02 :The working of compareTo() method in Java to compare two integer values.

Output :

Comparing num1 and num2: 1
Comparing num1 and num3: 0
Comparing num2 and num3: -1
Comment