java tutorial - Java compareTo() method - java programming - learn java - java basics - java for beginners



Java numbers compare to

Learn Java - Java tutorial - Java numbers compare to - Java examples - Java programs

  • The method compareTo () compares the numeric object that the method calls,
  • with the argument. When working with numbers, the compareTo () method in Java allows you to compare two numbers of the same type, for example, byte, long, integer, etc. However, you can not compare two different types of arguments and numeric objects, calling the method they must be of the same type.

Syntax

public int compareTo( NumberSubClass referenceName )
click below button to copy the code. By - java tutorial - team

Options

Detailed information about the parameters:

  • referenceName - must be byte, double, integer, float, long or short.

Return value

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

Sample Code

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));            
     }
}
click below button to copy the code. By - java tutorial - team

Output

1
0
-1

Related Searches to Java compareTo() method