Menu
Topics Index
...
`

DoubleFloatDemo - Java Example Program


DoubleFloatDemo
import java.util.*;

class DoubleFloatDemo
{
    public static void main(String arg[])
    {
        float f = 9.4f;
        Float f_obj = new Float(f); // LINE A
        //Compares the numeric values of two Float class objects
        System.out.println("Values when f_obj compared with f: " + f_obj.compareTo(f)); // LINE B
        //Compares the float object with any other object
        System.out.println("f_obj and f are equal: " + f_obj.equals(f)); // LINE C
        //Returns float equivalent of the string
        System.out.println("Float equivalent of string: " + Float.parseFloat("10")); // LINE D
        //Returns a string from a Float object
        System.out.println("String representation of Float: " + Float.toString(f_obj)); // LINE E    
    }
}
OUTPUT

Values when f_obj compared with f: 0
f_obj and f are equal: true
Float equivalent of string: 10.0
String representation of Float: 9.4

DESCRIPTION

At LINE A we have created a Float object with the value of f.
At LINE B we have compared f_obj and f with compareTowhich returned 0 since the values are same.
At LINE C we have compared f_obj and f with equals which returned true.
At LINE D we are converting a String value to Float object.
At LINE E we are converting a Float object to String object.

THINGS TO TRY
  • At LINE A instead of passing parameter f pass a value 9.4 to see a compilation error since 9.4 is a double value and the actual parameter to be passed is Float object compiler throws a compilation error.
    f_obj.compareTo(9.4));
    Note: When we pass any primitive value JVM automatically converts it to its equivalent wrapper class object.
  • At LINE B change the equals method parameter to 9.4 and see the output. The output will become false since the values 9.4f and 9.4 are not same.

© meritcampus 2019

All Rights Reserved.

Open In App