This blog will discuss the methods for comparing doubles in Java.
How to Compare doubles in Java?
To compare doubles in Java, you can use:
- compare() method
- compareTo() method
We will discuss each of the methods mentioned above one by one!
Method 1: Compare doubles in Java Using compare() Method
The “compare()” method is used to compare two specific double values. It is the static method of the Double Java wrapper class.
Syntax
The syntax of compare() method is:
Here, the compare() method takes two double type values “d1” and “d2” as arguments and returns integer type values: 1,-1, or 0 depending on conditions:
- It returns 1 if the first value is greater than the second.
- It will return -1 if the first double value is less than the second.
- Zero indicates that both double values are equal.
Have a look at the given examples for a better understanding.
Example
In this example, we will compare two double-type values, “db1” and “db2”, with “167.643” and “986.675”, where “d” indicates that it is a double type value:
We will compare the created doubles and store the returned value in “comp”:
Add the if-else-if conditions to check whether the compared values greater than, less than or equals to each other:
The given output indicates that the value of “db1” is less than “db2”:
Now, head towards the next method.
Method 2: Compare doubles in Java Using compareTo() Method
The “compareTo()” method is also used to compare doubles in Java, and it also belongs to the “Double” Java wrapper class. In this method, the first double value is compared to the second double value.
Syntax
The syntax of compareTo() method is:
Here, “d1” is compared to “d2” with the help of the “compareTo()” method.
Example
The values of two double type objects “db1” and “db2” of the Double class will be compared:
Here, we will pass “db2” as an argument to “db1”:
Specify the if-else-if conditions to check whether the compared values are greater than, less than, or equal to each other:
Execution of the above-given program will let you know that both values are the same:
We gathered all the essential instructions related to comparing doubles in Java.
Conclusion
To compare doubles in Java, we have two built-in methods of the Double Java wrapper class: the compare() method and the compareTo() method. Both return integer type values after comparing, where zero shows the values are equal while one indicates the first value is greater than the second value and -1 for its reverse. In this blog, we discussed the methods to compare doubles in Java.