Java compareTo() Method
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
-
Returns 0 if the specified number equals the argument.
-
Returns -1 if the specified number is less than the argument.
-
Returns 1 if the specified number is greater than the argument.
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
The Java Number class