java.lang.Double compare(double d1,double d2)
Syntax:
public static int compare(double d1,double d2)
Java Code Example :
This java example source code demonstrates the use of compare(double d1,double d2) method of Double class.
Some takeaways on this method:
- Compares 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)).
- 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.
- Since JDK 1.4
- Must be invoked statically.
package com.javatutorialhq.java.examples;
import static java.lang.System.out;
/*
* This example source code demonstrates the use of
* compare(double d1,double d2) method of Double class
*/
public class DoubleCompareTo {
public static void main(String[] args) {
Double val1 = 1.95;
Double val2 = 0.0 / 0.0;
Double val3 = 9.0 / 0;
Double val4 = -val1 / 0.0;
Double val5 = 3.25;
Double val6 = 0.0;
/*
* test all the possible scenario on using the
* compare(double d1,double d2) method
*/
out.println(val1 + " compare with " + val5 + " is?"
+ Double.compare(val1, val5));
out.println(val2 + " compare with " + val3 + " is?"
+ Double.compare(val2, val3));
out.println(val3 + " compare with " + val4 + " is?"
+ Double.compare(val3, val4));
out.println(val1 + " compare with " + val2 + " is?"
+ Double.compare(val1, val2));
out.println(val6 + " compare with " + val2 + " is?"
+ Double.compare(val6, val2));
out.println(val6 + " compare with " + val4 + " is?"
+ Double.compare(val6, val4));
}
}
Sample Output :
Running the above example source code will give the following output
1.95 compare with 3.25 is?-1 NaN compare with Infinity is?1 Infinity compare with -Infinity is?1 1.95 compare with NaN is?-1 0.0 compare with NaN is?-1 0.0 compare with -Infinity is?1