Home » Java programming language

Java Float class compare() method with example

Float class compare() method: Here, we are going to learn about the compare() method of Float class with its syntax and example.
Submitted by Preeti Jain, on October 04, 2019

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.


    public static int compare(float value1, float value2);


  • 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.


// 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);

        if (compare == 0)
            System.out.println("value1 is equal to value2");
        else if (compare < 0)
            System.out.println("value1 is less than value2");
            System.out.println("value1 is greater than value2");


Float.compare(value1,value2): -1

value1 is less than value2

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.