What is the Float.compare method in Java?
The compare method is a static method of the Float class that is used to compare two float values.
Syntax
public static int compare(float x, float y);
Parameters
The function takes in two float values as a parameter.
Return value
This method returns:
-
0if both the values are the same. -
A value less than zero if
xis less thany. -
A value greater than zero if the
xis greater thany.
Float.compare(x,y)
Case | Return Value |
x == y | 0 |
x < y | < 0 |
x > y | > 0 |
Code
The example below uses the Float.compare method:
class FloatCompare {public static void main( String args[] ) {float ten = 10f;float twenty = 20f;System.out.println("ten, ten : " + Float.compare(ten, ten));System.out.println("twenty, twenty : " + Float.compare(twenty, twenty));System.out.println("ten, twenty : " + Float.compare(ten, twenty));System.out.println("twenty, ten : " + Float.compare(twenty, ten));}}
Explanation
In the code above:
- We created two
floatvariables:
ten = 10f;
twenty = 20f;
- We used the
comparemethod of theFloatclass to compare thefloatvalues. - First, we compared the same values:
compare(ten,ten);
compare(twenty, twenty);
-
The
comparemethod returns0, as both the compared values are the same. -
Then, we compared
tenwithtwenty:
compare(ten, twenty);
-
The
comparemethod returns a value< 0because the first value is less than the second value. -
Then, we compared
twentywithten.
compare(twenty, ten);
- The
comparemethod returns a value> 0because the first value is greater than the second value.