Java Program to demonstrate Float wrapper class
Program
import java.lang.Float;
public class javaLangFloatDemo
{
public static void main (String[]args)
{
Float fObj = new Float(236.654);
System.out.println ("Value of Float object : " + fObj);
}
}
This Java program demonstrates the usage of the Float wrapper class, which provides an object representation for the primitive float data type.
1. Import Statement
import java.lang.Float;
- The
Floatclass is part of thejava.langpackage, which is automatically imported in Java. The explicitimportstatement is optional. Floatis a wrapper class that encapsulates afloatvalue in an object.
2. Class Definition
public class javaLangFloatDemo
- Defines the class
javaLangFloatDemo.
3. Main Method
public static void main (String[] args)
- Entry point for the program.
4. Create a Float Object
Float fObj = new Float(236.654);
FloatConstructor:- Creates an object of the
Floatwrapper class that stores the value236.654. - The constructor takes a
floatordoublevalue as its argument and wraps it into aFloatobject.
- Creates an object of the
- Note:
- The constructor
new Float(double value)is deprecated in modern Java versions. Instead, useFloat.valueOf(236.654f)or autoboxing (Float fObj = 236.654f;).
- The constructor
5. Print the Value
System.out.println ("Value of Float object : " + fObj);
- Prints the value stored in the
Floatobject. - The
toString()method of theFloatclass is implicitly called to convert the object to a string for display.
Key Concepts
-
Wrapper Classes:
- The
Floatwrapper class provides a way to representfloatvalues as objects. - Useful in scenarios where objects are required, such as collections (
ArrayList) or generic methods.
- The
-
Autoboxing and Unboxing:
- Autoboxing: Automatically converts a primitive
floatto aFloatobject. Example:Float fObj = 236.654f; // Autoboxing - Unboxing: Automatically converts a
Floatobject back to a primitivefloat. Example:float primitiveValue = fObj; // Unboxing
- Autoboxing: Automatically converts a primitive
-
Deprecated Constructor:
- Using
new Float(value)is discouraged in favor ofFloat.valueOf(value)in modern Java.
- Using
Output
Value of Float object : 236.654