Home » Java programming language

Java Float class compareTo() method with example

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

Float class compareTo() method

  • compareTo() method is available in java.lang package.
  • compareTo() method is used to check equality or inequality for this Float object against the given Float object mathematically or in other words, we can say this method is used to compare two Float objects.
  • compareTo() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • compareTo() method does not throw an exception at the time of comparing Float object.


    public int compareTo(Float value2);


  • Float value2 – represents the Float object to compare with.

Return value:

The return type of this method is int, it returns an integer value on the basis of following conditions,

  • It returns 0 if value2 is mathematically equal to value1.
  • It returns the value < 0 if value2 is mathematically greater than value1.
  • It returns the value > 0 if value2 is mathematically less than value1.


// Java program to demonstrate the example 
// of compareTo(Float value2) method of 
// Float class

public class CompareToOfFloatClass {
    public static void main(String[] args) {
        // Variables initialization
        float f1 = 30.20f;
        float f2 = 40.20f;

        // Float instance 
        Float value1 = new Float(f1);
        Float value2 = new Float(f2);

        // It compare two Float objects and placed the result 
        // in another variable (compare) of integer type
        int compare = value1.compareTo(value2);

        // Display result
        System.out.println("value1.compareTo(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");


value1.compareTo(value2): -1

value1 is less than value2


Comments and Discussions



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.