Java Tutorial

Java Control Statements

Object Oriented Programming

Java Built-in Classes

Java File Handling

Java Error & Exceptions

Java Multithreading

Java Synchronization

Java Networking

Java Collections

Java List Interface

Java Queue Interface

Java Map Interface

Java Set Interface

Java Data Structures

Java Collections Algorithms

Java Miscellaneous

Advanced Java

Java APIs & Frameworks

Java Useful Resources

Java - compareTo() Method



Description

The method compares the Number object that invoked the method to the argument. It is possible to compare Byte, Long, Integer, etc.

However, two different types cannot be compared, both the argument and the Number object invoking the method should be of the same 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 greater than the argument then 1 is returned.
  • If the Integer is equal to the argument then 0 is returned.
  • If the Integer is less than the argument then -1 is returned.

Example

public class Test {
   public static void main(String args[]) {
      Integer x = 5;
      //Integer value is greater than the argument (5>3) so, output is 1
      System.out.println(x.compareTo(3));
      //Integer value is equal to the argument so, output is 0
      System.out.println(x.compareTo(5));
      //Integer value is less than the argument (5<8) so, output is −1
      System.out.println(x.compareTo(8));            
   }
}

This will produce the following result −

Output

1
0
-1
java_numbers.htm
Advertisements