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 type Float that is compared with the caller Float object.

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.0f is considered to be greater than -0.0f.
  • Float.NaN is considered to be equal to Float.NaN and greater than all other values (including Float.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 Float object variable with the name val and value 10.55.

  • In line 4, we call the compareTo method on the val object with 10.55f as an argument. We get 0 as a result because the values are equal.

  • In line 5, we call the compareTo method on the val object with 11.55f as an argument. We get -1 as a result because the value of val is less than the argument.

  • In line 6, we call the compareTo method on the val object with 9.55f as an argument. We get 1 as a result because the value of val is greater than the argument.

  • In line 7, we call the compareTo method on the val object with Float.NaN as an argument. We get -1 as a result because Float.NaN is considered to be equal to Float.NaN and greater than all other values (including Float.POSITIVE_INFINITY).

Free Resources