logo

Java CompareTo() Method


Show

Description

The process compares the Number entity that appealed the technique to the argument. It is likely to compare Byte, Long, Integer, etc. However, two dissimilar types never are compared, both the argument and the Number object appealing the technique should be of a similar type.

Syntax

public int compareTo( NumberSubClass referenceName )

Parameters

Here is the detail of parameters −

  • referenceName − This could be a Byte, Double, Integer, Float, Long, or Short.

Return Value

  • If the Integer is equal to the argument then 0 is returned.
  • If the Integer is less than the argument then -1 is returned.
  • If the Integer is greater than the argument then 1 is returned.

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

This will produce the following result −

Output

1
0
-1

Here at Intellinuts, we have created a complete Java tutorial for Beginners to get started in Java.