Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does compareTo work with double type?

I need to make a program that uses compareTo, but I'm running into issues with it.

double sides1 = 1.0;
double sides2 = 1.3;
int compared = sides1.compareTo(sides2);

I always run into an error that says

Cannot invoke compareTo(double) on the primitive type double

What am I doing wrong, and how do I fix it?

like image 767
public static void Avatar asked Jun 03 '26 18:06

public static void


2 Answers

You cannot call methods on primitive values such as doubles. But you can call Double.compare, which will compare two primitive doubles for you.

int compared = Double.compare(sides1, sides2);

You can also compare primitive double values directly with the comparison operators ==, !=, <, <=, > and >=.

like image 71
rgettman Avatar answered Jun 05 '26 07:06

rgettman


A primitive type is not a Java Object and so the method compareTo does not exist. Use the Java Object Double and not the primitive type:

Double sides1 = Double.valueOf(1.0);
Double sides2 = Double.valueOf(1.3);
int compared = sides1.compareTo(sides2);

Edit - do not take from that that all Java Objects have the compareTo(..) method. The compareTo(..) is part of the Comparable Interface https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html

like image 44
doc Avatar answered Jun 05 '26 09:06

doc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!