The compare() method of Float Class is a built-in method in Java that compares the two specified float values. The sign of the integer value returned is the same as that of the integer that would be returned by the function call.
Syntax:
public static int compare(float f1, float f2)
Parameters: The function accepts two parameters:
- f1: The first float value to be compared.
- f2: The second float value to be compared.
Return Value: The function returns value as below:
- 0: if f1 is numerically equal to f2.
- Negative value: if f1 is numerically less than f2.
- Positive value: if f1 is numerically greater than f2.
Below programs illustrates the use of Float.compare() function:
Program 1: When two integers are same
Java
import java.lang.Float;
public class GFG {
public static void main(String[] args)
{
Float f1 = 1023f;
Float f2 = 1023f;
if (Float.compare(f1, f2) == 0 ) {
System.out.println( "f1=f2" );
}
else if (Float.compare(f1, f2) < 0 ) {
System.out.println( "f1<f2" );
}
else {
System.out.println( "f1>f2" );
}
}
}
|
Program 2 : When f1<f2
Java
import java.lang.Float;
public class GFG {
public static void main(String[] args)
{
Float f1 = 10f;
Float f2 = 1023f;
if (Float.compare(f1, f2) == 0 ) {
System.out.println( "f1=f2" );
}
else if (Float.compare(f1, f2) < 0 ) {
System.out.println( "f1<f2" );
}
else {
System.out.println( "f1>f2" );
}
}
}
|
Program 3 : When f1>f2
Java
import java.lang.Float;
public class GFG {
public static void main(String[] args)
{
Float f1 = 1023f;
Float f2 = 10f;
if (Float.compare(f1, f2) == 0 ) {
System.out.println( "f1=f2" );
}
else if (Float.compare(f1, f2) < 0 ) {
System.out.println( "f1<f2" );
}
else {
System.out.println( "f1>f2" );
}
}
}
|
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
05 Sep, 2023
Like Article
Save Article