Java.lang Package Classes

Java Double - compare() Method



The java.lang.Double.compare() method is used to compare the two specified double values. The sign of the integer value returned is the same as that of the integer that would be returned by the call: new Double(d1).compareTo(new Double(d2)).

Syntax

public static int compare(double d1,
                          double d2)

Parameters

d1 Specify the first double to compare.
d2 Specify the second double to compare.

Return Value

Returns the value 0 if d1 is numerically equal to d2; a value less than 0 if d1 is numerically less than d2; and a value greater than 0 if d1 is numerically greater than d2.

Exception

NA.

Example:

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

import java.lang.*;

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

    //comparing double values 
    System.out.println("comparing val1 and val2: " + Double.compare(val1, val2)); 
    System.out.println("comparing val1 and val3: " + Double.compare(val1, val3)); 
    System.out.println("comparing val3 and val1: " + Double.compare(val3, val1));    
  }
}

The output of the above code will be:

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

❮ Java.lang - Double