Search code examples
javanumberscompareto

How to compare the value of two Double objects using the compare() method?


I'm new to Java and is trying to learn the compare() method of Number class. I have declared two Double objects and tried to compare their values, however, the compiler prints out an error instead.

Why this is happening?

 Double i = new Double(3.4632);
 System.out.println(i.compareTo(m));
 Double m = new Double(96.235);

java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: <any>

Solution

  • If your code is actually as written (with the println before the declaration of m) then the problem is most likely that you're using m before it's declared. Move the println call to after the declaration:

        Double i = new Double(3.4632);
        Double m = new Double(96.235);
        System.out.println(i.compareTo(m));