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 the java.lang package, which is automatically imported in Java. The explicit import statement is optional.
  • Float is a wrapper class that encapsulates a float 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 value 236.654.
    • The constructor takes a float or double value as its argument and wraps it into a Float object.
  • Note:
    • The constructor new Float(double value) is deprecated in modern Java versions. Instead, use Float.valueOf(236.654f) or autoboxing (Float fObj = 236.654f;).

5. Print the Value

System.out.println ("Value of Float object : " + fObj);
  • Prints the value stored in the Float object.
  • The toString() method of the Float class is implicitly called to convert the object to a string for display.

Key Concepts

  1. Wrapper Classes:

    • The Float wrapper class provides a way to represent float values as objects.
    • Useful in scenarios where objects are required, such as collections (ArrayList) or generic methods.
  2. Autoboxing and Unboxing:

    • Autoboxing: Automatically converts a primitive float to a Float object. Example:
      Float fObj = 236.654f; // Autoboxing
      
    • Unboxing: Automatically converts a Float object back to a primitive float. Example:
      float primitiveValue = fObj; // Unboxing
      
  3. Deprecated Constructor:

    • Using new Float(value) is discouraged in favor of Float.valueOf(value) in modern Java.

Output

Value of Float object : 236.654