Export (0) Print
Expand All

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);

Parameters

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));   

    }
}
/*
Output:
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.

Community Additions

ADD
Show:
© 2014 Microsoft