Java compareTo() Method

Java Number类Java Number Class


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

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

Syntax

public int compareTo( NumberSubClass referenceName )

Parameters

referenceName-- Can be a parameter of type Byte, Double, Integer, Float, Long, or Short.

Return Value

  • Returns 0 if the specified number is equal to 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 result is:

1
0
-1

Java Number类Java Number Class

Other Extensions