Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java compareTo() Method

Java compareTo() Method

Java Number ClassThe Java Number class


The compareTo() method compares a Number object with the method's argument. It can be used to compare Byte, Long, Integer and so on.

This method is used to compare two values of the same data type; two values of different types cannot be compared with this method.

Syntax



public int compareTo( NumberSubClass referenceName )

Parameters

referenceName -- can be an argument of type Byte, Double, Integer, Float, Long or Short.

Return Value

Example

public

class

Test

{

public

static

void

main

(

String

args

[

]

)

{

Integer

x

=

5

;

System

.

out

.

println

(

x

.

compareTo

(

3

)

)

;

System

.

out

.

println

(

x

.

compareTo

(

5

)

)

;

System

.

out

.

println

(

x

.

compareTo

(

8

)

)

;

}

}

Compile the above program; the output is:



1

0

-1


Java Number ClassThe Java Number class