Java Double compare example



To compare Double in Java, use the following methods −

Method 1 − compareTo() method in Java

The java.lang.Double.compareTo() method compares two Double objects.

Example

 Live Demo

import java.lang.*;
public class Demo {
   public static void main(String args[]) {
      Double d1 = new Double("395.24");
      Double d2 = new Double("323.30");
      int res = d1.compareTo(d2);
      if(res > 0) {
         System.out.println("d1 is greater than d2");
      }
      else if(res < 0) {
         System.out.println("d1 is less than d2");
      }
      else {
         System.out.println("d1 is equal to d2");
      }
   }
}

Output

d1 is greater than d2

Method 2 − compare() method in Java

The java.lang.Double.compare() method compares two double values objects numerically.

Example

 Live Demo

import java.lang.*;
public class Demo {
   public static void main(String args[]) {
      Double d1 = new Double("195.24");
      Double d2 = new Double("323.30");
      int res = Double.compare(d1, d2);
      if(res > 0) {
         System.out.println("d1 is greater than d2");
      }
      else if(res < 0) {
         System.out.println("d1 is less than d2");
      }
      else {
         System.out.println("d1 is equal to d2");
      }
   }
}

Output

d1 is less than d2
karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know


Advertisements