Home » Java programming language

Java Integer Class compareTo() method with example

Integer class compareTo() method: Here, we are going to learn about the compareTo() method of Integer class with its syntax and example.
Submitted by Preeti Jain, on September 26, 2019

Integer class compareTo() method

  • compareTo() method is available in java.lang package.
  • compareTo() method is used to check equality or inequality for this Integer object against the given Integer object mathematically or in other words, we can say this method is used to compare two Integer objects.
  • compareTo() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • compareTo() method does not throw an exception at the time of comparing the Integer object.


    public int compareTo(Integer value2);


  • Integer value2 – represents the Integer object to compare with.

Return value:

The return type of this method is int, it returns an integer value.

  • It returns 0 if value1 is mathematically equal to value2.
  • It returns the value < 0 if value1 is mathematically less than value2.
  • It returns the value > 0 if value1 is mathematically greater than value2.


// Java program to demonstrate the example 
// of compareTo(Integer value2) method of Integer class

public class CompareToOfIntegerClass {
    public static void main(String[] args) {
        // Variables initialization
        int i1 = 10;
        int i2 = 20;

        // Integer instance 
        Integer value1 = new Integer(i1);
        Integer value2 = new Integer(i2);

        // It compare two Integer objects and placed the 
        // result in another variable (compare) of integer type
        int compare = value1.compareTo(value2);

        // Display result
        System.out.println("value1.compareTo(value2): " + compare);

        if (compare == 0)
            System.out.println("value1 is equal to value2");
        else if (compare < 0)
            System.out.println("value1 is less than value2");
            System.out.println("value1 is greater than value2");


value1.compareTo(value2): -1

value1 is less than value2

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.