java.lang.Float compare()
Description
Important Notes:
- The method
compare(float f1, float f2)
will yield the same result asnew Float(f1).compareTo(new Float(f2))
Method Syntax
public static int compare(float f1, float f2)
Method Argument
Data Type | Parameter | Description |
---|---|---|
float | f1 | the first float to compare |
float | f2 | the second float to compare |
Method Returns
The compare() method of Float class returns the value 0 if f1 is numerically equal to f2; a value less than 0 if f1 is numerically less than f2; and a value greater than 0 if f1 is numerically greater than f2.
Discussion
Java Float comapre(float f1, float f2) Example
Below is a simple java example on the usage of compare() method of Float class.
package com.javatutorialhq.java.examples; import java.util.Scanner; import static java.lang.System.*; /* * This example source code demonstrates the use of * compare(float f1, float f2) method of Float class. */ public class FloatCompareExample { public static void main(String[] args) { // Ask user input for first number System.out.print("Enter First Number:"); // declare the scanner object Scanner scan = new Scanner(System.in); // use scanner to get value from user console Float f1 = scan.nextFloat(); // Ask user input for second number System.out.print("Enter Second Number:"); Float f2 = scan.nextFloat(); // close the scanner object scan.close(); int result = Float.compare(f1, f2); System.out.println("Result of comparing f1 and f2:" + result); if (result == 1) { out.println("f1 is greater than f2"); } else if (result == 0) { out.println("f1 is equal to f2"); } else { out.println("f1 is less than f2"); } } }
Basically on the above example, we just ask for two numbers on the console and then we use the scanner object to get the float inputs. We then determine which of the two numbers were higher using the compare method.
Sample Output
Below is the sample output when you run the above example.