java.lang.Integer compareTo(Integer anotherInteger)

Description :

This java tutorial shows how to use the compareTo() method of Integer class under java.lang package. This method return an int which corresponds to the equality of the method argument and this Integer.

Method Syntax :

public int compareTo(Integer anotherInteger)

Parameter Input :

 

DataType Parameter Description
Integer anotherInteger the integer value that we want to compare on this Integer object

 

Method Returns :

The compareTo(Integer anotherInteger) method simply returns the result of comparing anotherInteger to this Integer object.

Compatibility Version :

Requires Java 1.2 and up

Exception :

N/A

Discussion :

The compareTo method of Integer class is specified by Comparable interface. This method simply just a way to compare this Integer object to the Integer method argument. The following values will be returned by this method:

  • 0 if the method argument Integer is equal to this Integer object.
  • a value greater than 0 if this integer is numerically greater than the Integer method argument.
  • a value less than 0 if this Integer object is numerically less than the Integer method argument.

Java Code Example :

This java example source code demonstrates the use of compareTo() method of Integer class. Basically we just explore all the possibilities that the compareTo method can offer.

package com.javatutorialhq.java.examples;

import static java.lang.System.*;

/*
 * This example source code demonstrates 
 * the use of compareTo method of Integer class
 */

public class IntegerCompareTo {

	public static void main(String[] args) {
		// declare the Integer object
		Integer value = new Integer(100);
		// check if the value is less than 100
		out.println(value.compareTo(99));
		// check if value is equal to 100
		out.println(value.compareTo(100));
		// check if value is greater than 100
		out.println(value.compareTo(101));

	}

}

Sample Output :

Running the compareTo(Integer anotherInteger) method example source code of Integer class will give you the following output

java integer compareto method example

java integer compareto method example

Exception Scenario :

N/A

Similar Method :

  • N/A

Suggested Reading List :

References :