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);
}
}
Purpose
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
Float
class is part of thejava.lang
package, which is automatically imported in Java. The explicitimport
statement is optional. Float
is a wrapper class that encapsulates afloat
value 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);
Float
Constructor:- Creates an object of the
Float
wrapper class that stores the value236.654
. - The constructor takes a
float
ordouble
value as its argument and wraps it into aFloat
object.
- 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
Float
object. - The
toString()
method of theFloat
class is implicitly called to convert the object to a string for display.
Key Concepts
-
Wrapper Classes:
- The
Float
wrapper class provides a way to representfloat
values 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
float
to aFloat
object. Example:Float fObj = 236.654f; // Autoboxing
- Unboxing: Automatically converts a
Float
object 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