Convert String To Float in Java

1. Introduction

Converting strings to floats in Java is commonly required when dealing with numeric data that comes as text, such as user input, file data, or network responses. Java provides several ways to perform this conversion, the most popular being Float.parseFloat() for primitive float values and Float.valueOf() for Float objects. This tutorial explores both methods.

Key Points

- Float.parseFloat(String s) converts a string to a primitive float.

- Float.valueOf(String s) returns a Float object.

- Both methods can throw NumberFormatException if the string is not a valid float.

2. Program Steps

1. Define a string that represents a float value.

2. Convert the string to a primitive float using Float.parseFloat().

3. Convert the string to a Float object using Float.valueOf().

4. Print both converted values.

3. Code Program

public class StringToFloatExample {
    public static void main(String[] args) {
        // String to be converted
        String floatString = "3.14";

        // Convert string to primitive float
        float floatPrimitive = Float.parseFloat(floatString);

        // Convert string to Float object
        Float floatObject = Float.valueOf(floatString);

        // Print the results
        System.out.println("Converted to primitive float: " + floatPrimitive);
        System.out.println("Converted to Float object: " + floatObject);
    }
}

Output:

Converted to primitive float: 3.14
Converted to Float object: 3.14

Explanation:

1. String floatString = "3.14": Declares and initializes a string that contains a numerical value suitable for conversion to float.

2. float floatPrimitive = Float.parseFloat(floatString): Converts the string to a primitive float using Float.parseFloat(). This is useful for situations where we need to use the float value in calculations or operations that do not require object references.

3. Float floatObject = Float.valueOf(floatString): Converts the string to a Float object using Float.valueOf(). This is useful for cases where float values need to be treated as objects, such as in collections or where method calls require objects.

4. System.out.println("Converted to primitive float: " + floatPrimitive) and System.out.println("Converted to Float object: " + floatObject): Prints both the primitive float and the Float object to the console, demonstrating the successful conversion of the string to float in both forms.


Comments