Java.lang Package Classes

Java Double - compareTo() Method



The java.lang.Double.compareTo() method is used to compare two Double objects numerically. There are two ways in which comparisons performed by this method differ from those performed by the Java language numerical comparison operators (<, <=, ==, >=, >) when applied to primitive double values:

  • Double.NaN is considered by this method to be equal to itself and greater than all other double values (including Double.POSITIVE_INFINITY).
  • 0.0d is considered by this method to be greater than -0.0d.

Syntax

public int compareTo(Double anotherDouble)

Parameters

anotherDouble Specify the Double to be compared.

Return Value

Returns the value 0 if anotherDouble is numerically equal to this Double; a value less than 0 if this Double is numerically less than anotherDouble; and a value greater than 0 if this Double is numerically greater than anotherDouble.

Exception

NA.

Example:

In the example below, the java.lang.Double.compareTo() method is used to compare given Double objects.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    
    //creating Double objects
    Double val1 = 5.2;
    Double val2 = 5.2;
    Double val3 = -5.2;

    //comparing Double objects 
    System.out.println("comparing val1 with val2: " + val1.compareTo(val2)); 
    System.out.println("comparing val1 with val3: " + val1.compareTo(val3)); 
    System.out.println("comparing val3 with val1: " + val3.compareTo(val1));    
  }
}

The output of the above code will be:

comparing val1 with val2: 0
comparing val1 with val3: 1
comparing val3 with val1: -1

❮ Java.lang - Double