Skip to Content

Java Float Compare Example

  1. /*
  2.   Java Float compare example
  3.   This example shows how to compare a Float object with other Float object, Float
  4.   with an Object, or two float primitive values using methods provided by
  5.   java.lang.Float class.
  6. */
  7.  
  8. public class JavaFloatCompareExample {
  9.  
  10.   public static void main(String[] args) {
  11.    
  12.     /*
  13.     To compare two float primitive values use
  14.     compare(float f1, float f2) method of Float class. This is a static method.
  15.     It returns 0 if both the values are equal, returns value less than 0 if
  16.     f1 is less than f2, and returns value grater than 0 if f2 is grater than f2.
  17.     */
  18.     float f1 = 5.35f;
  19.     float f2 = 5.34f;
  20.     int i1 = Float.compare(f1,f2);
  21.    
  22.     if(i1 > 0){
  23.       System.out.println("First is grater");
  24.     }else if(i1 < 0){
  25.       System.out.println("Second is grater");
  26.     }else{
  27.       System.out.println("Both are equal");
  28.     }
  29.    
  30.     /*
  31.     To compare a Float object with another Float object use
  32.     int compareTo(Float f) method.
  33.     It returns 0 if both the values are equal, returns value less than 0 if
  34.     this Float object is less than the argument, and returns value grater
  35.     than 0 if this Float object is grater than f2.
  36.     */
  37.     Float fObj1 = new Float("5.35");
  38.     Float fObj2 = new Float("5.34");
  39.     int i2 = fObj1.compareTo(fObj2);
  40.    
  41.     if(i2 > 0){
  42.       System.out.println("First is grater");
  43.     }else if(i2 < 0){
  44.       System.out.println("Second is grater");
  45.     }else{
  46.       System.out.println("Both are equal");
  47.     }  
  48.    
  49.    
  50.   }
  51. }
  52.  
  53. /*
  54. Output would be
  55. First is grater
  56. First is grater
  57. */

Advertisement: