Java Integer compareTo() method
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 : To show working of java.lang.Integer.compareTo() method.
// Java program to demonstrate working // of java.lang.Integer.compareTo() method import java.lang.Integer; class Gfg { // driver code public static void main(String args[]) { Integer a = new Integer(10); Integer b = new Integer(20); // as 10 less than 20, Output will be a value less than zero System.out.println(a.compareTo(b)); Integer x = new Integer(30); Integer y = new Integer(30); // as 30 equals 30, Output will be zero System.out.println(x.compareTo(y)); Integer w = new Integer(15); Integer z = new Integer(8); // as 15 is greater than 8, Output will be a value greater than zero System.out.println(w.compareTo(z)); } } |
Output:
-1 0 1
Recommended Posts:
- LocalDate compareTo() method in Java
- CharBuffer compareTo() method in Java
- YearMonth compareTo() method in Java
- BigInteger compareTo() Method in Java
- IntBuffer compareTo() method in Java
- ChronoZonedDateTime compareTo() method in Java with Examples
- MonthDay compareTo() method in Java with Examples
- OffsetTime compareTo() method in Java with examples
- FloatBuffer compareTo() method in Java With Examples
- ChronoLocalDate compareTo() method in Java with Examples
- Byte compareTo() method in Java with examples
- Instant compareTo() method in Java with Examples
- Date compareTo() method in Java with examples
- OffsetDateTime compareTo() method in Java with examples
- Calendar compareTo() Method in Java with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



