What is the Float.compareTo method in Java?
The compareTo() method of the Float class can be used to compare the current object’s Float value to another Float object’s value.
Syntax
public int compareTo(Float b);
Parameters
The compareTo() method takes one parameter:
b: an object of typeFloatthat is compared with the callerFloatobject.
Return value
-
0, if the current object value and the passed argument value are the same. -
A positive value, if the current object value is greater than the passed argument.
-
A negative value, if the current object value is less than the passed argument.
Attributes of compareTo()
0.0fis considered to be greater than-0.0f.Float.NaNis considered to be equal toFloat.NaNand greater than all other values (includingFloat.POSITIVE_INFINITY).
Code
The code below uses the compareTo() method to compare the Float values as follows.
class FloatompareToExample {public static void main( String args[] ) {Float val = 10.55f;System.out.println("10.55, 10.55 : " + val.compareTo(10.55f));System.out.println("10.55, 11.55 : " + val.compareTo(11.55f));System.out.println("10.55, 9.55 : " + val.compareTo(9.55f));System.out.println("10.55, Float.NaN : " + val.compareTo(Float.NaN));}}
Explanation
In the code above:
-
In line 3, we create a
Floatobject variable with the namevaland value10.55. -
In line 4, we call the
compareTomethod on thevalobject with10.55fas an argument. We get0as a result because the values are equal. -
In line 5, we call the
compareTomethod on thevalobject with11.55fas an argument. We get-1as a result because the value ofvalis less than the argument. -
In line 6, we call the
compareTomethod on thevalobject with9.55fas an argument. We get1as a result because the value ofvalis greater than the argument. -
In line 7, we call the
compareTomethod on thevalobject withFloat.NaNas an argument. We get-1as a result becauseFloat.NaNis considered to be equal toFloat.NaNand greater than all other values (includingFloat.POSITIVE_INFINITY).