What is the Double.compare method in Java?

compare is a static method of the Double class which is used to compare two double values.

Syntax

public static int compare(double x, double y);

Parameters

The function takes in two double values as a parameter.

Return value

This method returns:

  • 0 if both the values are the same.

  • A value less than zero, if x is less than y.

  • A value greater than zero, if the x is greater than y.

Double.compare(x,y)

Case

Retturn Value

x == y

0

x < y

< 0

x > y

> 0

Code

class DoubleCompare {
public static void main( String args[] ) {
double ten = 10d;
double twenty = 20d;
System.out.println("ten, ten : " + Double.compare(ten, ten));
System.out.println("twenty, twenty : " + Double.compare(twenty, twenty));
System.out.println("ten, twenty : " + Double.compare(ten, twenty));
System.out.println("twenty, ten : " + Double.compare(twenty, ten));
}
}

Explanation

In the code above:

  • We created two double variables:
ten = 10d;
twenty = 20d;
  • We used the compare method of the Double class to compare the double values. First, we compared the same values:
compare(ten,ten);
compare(twenty, twenty);

The compare method returns 0, as both the compared values are the same.

  • Then, we compared ten with twenty:
compare(ten, twenty);

The compare method returns a value < 0, as the first value is less than the second value.

  • Then, we compared twenty with ten.
compare(twenty, ten);

The compare method returns a value > 0, as the first value is greater than the second value.

Free Resources