Open In App

Float compare() Method in Java with Examples

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:  

Return Value: The function returns value as below:  



Below programs illustrates the use of Float.compare() function:

Program 1: When two integers are same  




// Java Program to illustrate
// the Float.compare() method
 
import java.lang.Float;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // Get the two float values
        // to be compared
        Float f1 = 1023f;
        Float f2 = 1023f;
 
        // function call to compare two float values
        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");
        }
    }
}

Output
f1=f2


Program 2 : When f1<f2




// Java Program to illustrate
// the Float.compare() method
 
import java.lang.Float;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // Get the two float values
        // to be compared
        Float f1 = 10f;
        Float f2 = 1023f;
 
        // function call to compare two float values
        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");
        }
    }
}

Output
f1<f2

Program 3 : When f1>f2




// Java Program to illustrate
// the Float.compare() method
import java.lang.Float;
 
public class GFG {
    public static void main(String[] args)
    {
        // Get the two float values
        // to be compared
        Float f1 = 1023f;
        Float f2 = 10f;
 
        // function call to compare two float values
        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");
        }
    }
}

Output
f1>f2

 


Article Tags :