The Float
class in Java is a wrapper class for the primitive data type float
. It provides a number of methods for converting between float
and String
, as well as other useful methods for working with floating-point numbers.
Following is a quick overview of some of the key features of the Float
class:
Constructors
The Float
class has two constructors:
Constructor | Description |
---|---|
Float(float value) | Creates a new Float object with the specified value. |
Float(String value) | Creates a new Float object with the value represented by the specified string. |
Methods
The Float
class has a number of methods for working with floating-point numbers. Some of them are listed below:
Method | Description |
---|---|
floatValue() | Returns the primitive float value of the Float object. |
toString() | Returns a string representation of the Float object. |
parseFloat(String str) | Parses the specified string and returns a new Float object with the parsed value. |
isNaN() | Returns true if the specified float value is NaN (Not a Number). |
isInfinite() | Returns true if the specified float value is infinite. |
Following is a simple example of how to use the Float
class:
public class FloatDemo {
public static void main(String[] args) {
float f = 10.5f;
Float fObj = new Float(f);
System.out.println("f: " + f);
System.out.println("fObj: " + fObj);
String str = "12.34";
Float f2 = Float.parseFloat(str);
System.out.println("f2: " + f2);
if (Float.isNaN(f2)) {
System.out.println("f2 is NaN");
} else if (Float.isInfinite(f2)) {
System.out.println("f2 is infinite");
} else {
System.out.println("f2 is a finite number");
}
}
}
This code will print the following output:
f: 10.5
fObj: 10.5
f2: 12.34
f2 is a finite number