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:
-
0if both the values are the same. -
A value less than zero, if
xis less thany. -
A value greater than zero, if the
xis greater thany.
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
doublevariables:
ten = 10d;
twenty = 20d;
- We used the
comparemethod of theDoubleclass to compare thedoublevalues. 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
tenwithtwenty:
compare(ten, twenty);
The compare method returns a value < 0, as the first value is less than the second value.
- Then, we compared
twentywithten.
compare(twenty, ten);
The compare method returns a value > 0, as the first value is greater than the second value.