Java Float compareTo() Method
Java compareTo()
method belongs to the Float class. This method is similar to the compare()
method of the same class but the only difference is that here the Float Objects are compared numerically rather than the float values.
The object1.compareTo(float object2)
method returns the value
-
0; if object1 is equal to object2
-
-1; if object1 is less than object2
-
1; if object1 is greater than object2
Syntax:
public int compareTo(Float f2)
Parameter:
The parameter includes the Float object to be compared.
Returns:
0, -1, 1 depending upon the value of the argument float value.
Example 1:
Here, four objects n1, n2, n3, n4 are taken with respective float values and are checked for the values are either less, more, or equal than the compared values.
import java.lang.Float;
public class StudyTonight
{
public static void main(String[] args)
{
Float ob1 = 100.0f;
Float ob2 = 200.0f;
Float ob3 = 300.0f;
Float ob4 = 100.0f;
System.out.println(ob1.compareTo(ob2)); //Output will be less than zero
System.out.println(ob3.compareTo(ob1)); // Output will be greater than zero
System.out.println(ob1.compareTo(ob4)); // Output will be equal to zero
}
}
-1
1
0
Example 2:
Here, an array of Float objects is created and every object in the array is compared with the first object of the array.
import java.lang.Float;
public class StudyTonight
{
public static void main(String[] args)
{
Float [] ob = {-100.0f,-200.0f,300.0f,-100.0f};
for(int i=0;i<4;i++)
{
System.out.println(ob[0].compareTo(ob[i])); // comparing each object of array with first object
}
}
}
0
1
-1
0
Example 3:
Here is a general example where the user can enter the numbers of his choice and get the desired output. The try
and catch
block is used for handling any exception taking place during the execution of the program. (For example, the user enters a String, etc. in place of the float value).
import java.util.Scanner;
import java.lang.Float;
public class StudyTonight
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter first and second number ");
try
{
Float n1 = sc.nextFloat();
Float n2 = sc.nextFloat();
int r = n1.compareTo(n2);
if(r > 0)
{
System.out.println("first number is greater");
}
else if(r< 0)
{
System.out.println("second number is greater");
}
else
{
System.out.println("both numbers are equal");
}
}
catch(Exception e)
{
System.out.println("Error!!");
}
}
}
Enter first and second number 67.12 90.34
second number is greater
***************************************************
Enter first and second number 909.46 100.3
first number is greater
***************************************************
Enter first and second number 0x598 89
Error!!
Live Example:
Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.