compare
is a static method of the Double
class which is used to compare two double
values.
public static int compare(double x, double y);
The function takes in two double
values as a parameter.
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
.
Case | Retturn Value |
x == y | 0 |
x < y | < 0 |
x > y | > 0 |
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));}}
In the code above:
double
variables:ten = 10d;
twenty = 20d;
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.
ten
with twenty
:compare(ten, twenty);
The compare
method returns a value < 0
, as the first value is less than the second value.
twenty
with ten
.compare(twenty, ten);
The compare
method returns a value > 0
, as the first value is greater than the second value.