Core Java
Java Float Datatype Example
In Java, the Float class wraps a value of primitive type float in an object. An object of type Float contains a single field whose type is float.
In addition, this class provides several methods for converting a float to a String and a String to float, as well as other constants and methods useful when dealing with float. Let us look at some of the common methods used with an example.
1. Float datatype
Some of the commonly used methods of Float are:
int compareTo(Float anotherFloat)
: compares two Float objects numericallydouble doubleValue()
: Returns the value of this Float as a double after a widening primitive conversionboolean equals(Object obj)
: Compares this object against the specified objectfloat floatValue()
: Returns the float value of this Float objectint intValue()
: Returns the value of this Float as an int after a narrowing primitive conversionboolean isNaN()
: Returns true if this Float value is a Not-a-Number (NaN), false otherwiselong longValue()
: Returns value of this Float as a long after a narrowing primitive conversionstatic float parseFloat(String s)
: Returns a new float initialized to the value represented by the specified String, as performed by the valueOf method of class FloatString toString()
: Returns a string representation of thisFloat
objectstatic Float valueOf(String s)
: Returns a Float object holding the float value represented by the argument string s
2. Java Float data type example
Let us now look at an example using all the methods discussed above.
FloatExample
public class FloatExample{ public static void main(String args[]){ float a = 10.25F; float b = 23.22F; Float aF = new Float(a); Float bF = new Float(b); // compareTo(Float) System.out.println("aF.compareTo(bF) :"+aF.compareTo(bF)); // doubleValue() System.out.println("doubleValue(aF) :"+aF.doubleValue()); // equals(Object) System.out.println("equals(Object) :"+aF.equals(bF)); // floatValue() System.out.println("aF.floatValue :"+aF.floatValue()); // intValue() System.out.println("bF.intValue :"+bF.intValue()); // isNan() System.out.println("bF.isNan() :"+bF.isNaN()); // longValue() System.out.println("bF.longValue :"+bF.longValue()); // parseFloat System.out.println("parseFloat :"+Float.parseFloat("57.86")); } }
The output for the above class would be as follows:
aF.compareTo(bF) :-1 doubleValue(aF) :10.25 equals(Object) :false aF.floatValue :10.25 bF.intValue :23 bF.isNan() :false bF.longValue :23 parseFloat :57.86
3. Download the Source Code
Download
You can download the full source code of this example here: Java Float Datatype Example
You can download the full source code of this example here: Java Float Datatype Example