compareTo Method (Object)
Collapse the table of content
Expand the table of content
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer

Integer.compareTo Method (Object)

Visual Studio 2005

Compares the Integer current object to another object, which may or may not be an Integer. In the later case it throws an exception.

Package: java.lang

Assembly: vjslib (in vjslib.dll)

public int compareTo(
    java.lang.Object anInt);



The object to compare to.

0 if the two objects are identical. -1 if the parameter is greater than the object. 1 if the parameter is less than the object.

In this example, two Integer objects are created and compared. Depending on the value of the parameter compared to the value of the object the returned value take one of three values -1, 0, and 1.

A fourth comparison is made between an Integer and a Double object, but the statement is commented. If you uncomment the statement it will throw an exception.

// i-compareTo2.jsl
// compareTo Example

public class MyClass
    public static void main(String[] args)
        Integer i1 = new Integer(125);
        Integer i2 = new Integer(123);
        Double i3 = new Double(12.3);

        System.out.println("The comparison result = "+
                           i1.compareTo(i2));   // 1
        System.out.println("The comparison result = "+
                           i2.compareTo(i1));   // -1
        System.out.println("The comparison result = "+
                           i1.compareTo(i1));   // 0
        // The following line throws an exception:
        // System.out.println("The comparison result = "+
        //                   i1.compareTo(i3));   

The comparison result = 1
The comparison result = -1
The comparison result = 0

If the parameter objects are an Integer, the program will throw a java.lang.ClassCastException exception.

© 2016 Microsoft