java.lang.Double compareTo(Double anotherDouble)
Syntax:
public int compareTo(Double anotherDouble)
Java Code Example :
This java example source code demonstrates the use of compareTo(Double anotherDouble) method of Double class.
Some takeaways on the compareTo(Double anotherDouble) method:
- Compares two Double objects numerically.
- Double.NaN is considered by this method to be equal to itself and greater than all other double values (including Double.POSITIVE_INFINITY).
- 0.0d is considered by this method to be greater than -0.0d.
- returns the value 0 if anotherDouble is numerically equal to this Double; a value less than 0 if this Double is numerically less than anotherDouble; and a value greater than 0 if this Double is numerically greater than anotherDouble.
- Since JDK 1.2
package com.javatutorialhq.java.examples; import static java.lang.System.out; /* * This example source code demonstrates the use of * compareTo(Double anotherDouble) method of Double class */ public class DoubleCompareTo { public static void main(String[] args) { Double val1 = 100.25; Double val2 = 0.0 / 0.0; Double val3 = 9.0 / 0; Double val4 = -val1 / 0.0; Double val5 = 300.25; Double val6 = 0.0; /* * test all the possible scenario on using the * compareTo(Double anotherDouble) method */ out.println(val1 + " compare to " + val5 + " is?" + val1.compareTo(val5)); out.println(val2 + " compare to " + val3 + " is?" + val2.compareTo(val3)); out.println(val3 + " compare to " + val4 + " is?" + val2.compareTo(val3)); out.println(val1 + " compare to " + val2 + " is?" + val1.compareTo(val2)); out.println(val6 + " compare to " + val2 + " is?" + val6.compareTo(val2)); out.println(val6 + " compare to " + val4 + " is?" + val6.compareTo(val4)); } }
Sample Output :
Running the above example source code will give the following output
100.25 compare to 300.25 is?-1 NaN compare to Infinity is?1 Infinity compare to -Infinity is?1 100.25 compare to NaN is?-1 0.0 compare to NaN is?-1 0.0 compare to -Infinity is?1