Home »
Java programming language
Java - Float Class compare() Method
Float class compare() method: Here, we are going to learn about the compare() method of Float class with its syntax and example.
By Preeti Jain Last updated : March 21, 2024
Float class compare() method
- compare() method is available in java.lang package.
- compare() method is used to check equality or inequality of the given two float values or in other words, we can say this method is used to compare two float values.
- compare() method is a static method, it is accessible with the class name too and if we try to access the method with a class object then also, we will not get an error.
- compare() method does not throw an exception at the time of comparing float values.
Syntax
public static int compare(float value1, float value2);
Parameters
- float value1, float value2 – represent the float values to be compared.
Return Value
The return type of this method is int, it returns an integer value, based on the following conditions,
- It returns 0 if value1 is mathematically equal to value2.
- It returns the value < 0 if value1 is mathematically less than value2.
- It returns the value > 0 if value1 is mathematically greater than value2.
Example
// Java program to demonstrate the example
// of compare(float value1,float value2)
// method of Float class
public class CompareOfFloatClass {
public static void main(String[] args) {
// Variables initialization
float value1 = 18.20f;
float value2 = 20.20f;
// It compare two float values and placed the result
// in another variable (compare) of integer type
int compare = Float.compare(value1, value2);
// Display result
System.out.println("Float.compare(value1,value2): " + compare);
System.out.println();
if (compare == 0)
System.out.println("value1 is equal to value2");
else if (compare < 0)
System.out.println("value1 is less than value2");
else
System.out.println("value1 is greater than value2");
}
}
Output
Float.compare(value1,value2): -1
value1 is less than value2