Skip to Content

Java Double compare example

  1. /*
  2.   Java Double compare example
  3.   This example shows how to compare a Double object with other Double object, Double
  4.   with an Object, or two double primitive values using methods provided by
  5.   java.lang.Double class.
  6. */
  7.  
  8. public class JavaDoubleCompareExample {
  9.  
  10.   public static void main(String[] args) {
  11.    
  12.     /*
  13.     To compare two double primitive values use
  14.     compare(double d1, double d2) method of Double class. This is a static method.
  15.     It returns 0 if both the values are equal, returns value less than 0 if
  16.     d1 is less than d2, and returns value grater than 0 if d1 is grater than d2.
  17.     */
  18.     double d1 = 5.35;
  19.     double d2 = 5.34;
  20.     int i1 = Double.compare(d1,d2);
  21.    
  22.     if(i1 > 0){
  23.       System.out.println("First is grater");
  24.     }else if(i1 < 0){
  25.       System.out.println("Second is grater");
  26.     }else{
  27.       System.out.println("Both are equal");
  28.     }
  29.    
  30.     /*
  31.     To compare a Double object with another Double object use
  32.     int compareTo(Double d) method.
  33.     It returns 0 if both the values are equal, returns value less than 0 if
  34.     this Double object is less than the argument, and returns value grater
  35.     than 0 if this Double object is grater than the argument.
  36.     */
  37.     Double dObj1 = new Double("5.35");
  38.     Double dObj2 = new Double("5.34");
  39.     int i2 = dObj1.compareTo(dObj2);
  40.    
  41.     if(i2 > 0){
  42.       System.out.println("First is grater");
  43.     }else if(i2 < 0){
  44.       System.out.println("Second is grater");
  45.     }else{
  46.       System.out.println("Both are equal");
  47.     }    
  48.    
  49.    
  50.   }
  51. }
  52.  
  53. /*
  54. Output would be
  55. First is grater
  56. First is grater
  57. */