Java.lang Package Classes

Java Float - compareTo() Method



The java.lang.Float.compareTo() method is used to compare two Float objects numerically. There are two ways in which comparisons performed by this method differ from those performed by the Java language numerical comparison operators (<, <=, ==, >=, >) when applied to primitive float values:

  • Float.NaN is considered by this method to be equal to itself and greater than all other float values (including Float.POSITIVE_INFINITY).
  • 0.0f is considered by this method to be greater than -0.0f.

Syntax

public int compareTo(Float anotherFloat)

Parameters

anotherFloat Specify the Float to be compared.

Return Value

Returns the value 0 if anotherFloat is numerically equal to this Float; a value less than 0 if this Float is numerically less than anotherFloat; and a value greater than 0 if this Float is numerically greater than anotherFloat.

Exception

NA.

Example:

In the example below, the java.lang.Float.compareTo() method is used to compare given Float objects.

import java.lang.*;

public class MyClass {
  public static void main(String[] args) {
    
    //creating Float objects
    Float val1 = 5f;
    Float val2 = 5f;
    Float val3 = -5f;

    //comparing Float objects 
    System.out.println("comparing val1 with val2: " + val1.compareTo(val2)); 
    System.out.println("comparing val1 with val3: " + val1.compareTo(val3)); 
    System.out.println("comparing val3 with val1: " + val3.compareTo(val1));    
  }
}

The output of the above code will be:

comparing val1 with val2: 0
comparing val1 with val3: 1
comparing val3 with val1: -1

❮ Java.lang - Float