Java Float Class

Introduction

The Float class in Java is a wrapper for the primitive type float. It provides methods for converting and manipulating float values, handling floating-point arithmetic, and comparing floats.

Table of Contents

  1. What is Float?
  2. Creating Float Instances
  3. Common Methods
  4. Examples of Float
  5. Conclusion

1. What is Float?

Float is a final class that wraps a float value in an object. It offers methods for converting between float and String, performing numerical operations, and handling special float values like NaN and infinity.

2. Creating Float Instances

You can create Float instances in several ways:

  • Using the Float constructor: new Float(float value) or new Float(String value)
  • Using the Float.valueOf(float value) or Float.valueOf(String value) methods

3. Common Methods

  • floatValue(): Returns the value of this Float as a primitive float.
  • toString(): Returns a String representation of the float value.
  • parseFloat(String s): Parses a String to a primitive float.
  • isNaN(): Checks if the Float value is NaN (Not-a-Number).
  • isInfinite(): Checks if the Float value is infinite.
  • compare(Float f1, Float f2): Compares two Float objects.

4. Examples of Float

Example 1: Creating Float Instances

This example demonstrates how to create Float instances using constructors and valueOf methods.

public class FloatInstanceExample { public static void main(String[] args) { Float f1 = new Float(10.5f); Float f2 = Float.valueOf(20.5f); Float f3 = Float.valueOf("30.5"); System.out.println("f1: " + f1); System.out.println("f2: " + f2); System.out.println("f3: " + f3); } } 

Output:

f1: 10.5 f2: 20.5 f3: 30.5 

Example 2: Parsing a String to float

This example shows how to parse a String to a primitive float using parseFloat.

public class ParseFloatExample { public static void main(String[] args) { float f1 = Float.parseFloat("50.5"); float f2 = Float.parseFloat("100.75"); System.out.println("f1: " + f1); System.out.println("f2: " + f2); } } 

Output:

f1: 50.5 f2: 100.75 

Example 3: Checking NaN and Infinity

In this example, we demonstrate how to check for NaN and infinity.

public class NaNInfinityExample { public static void main(String[] args) { Float f1 = Float.NaN; Float f2 = Float.POSITIVE_INFINITY; System.out.println("f1 is NaN: " + f1.isNaN()); System.out.println("f2 is Infinite: " + f2.isInfinite()); } } 

Output:

f1 is NaN: true f2 is Infinite: true 

Conclusion

The Float class in Java is a useful wrapper for the primitive float type. It provides methods for converting, manipulating, and handling float values.

Leave a Comment

Scroll to Top