Convert String to Double in Java

1. Introduction

Converting a string to a double is a common task in Java, especially when dealing with numerical input from file reads, user inputs, or network communications. In Java, this conversion can be achieved using several methods, primarily through the Double.parseDouble() method and the Double.valueOf() method. This tutorial will demonstrate both methods to convert a string into a double.

Key Points

- Double.parseDouble(String s) returns a primitive double value.

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

- Both methods throw NumberFormatException if the string cannot be parsed as a double.

2. Program Steps

1. Define a string that represents a double value.

2. Convert the string to a double using Double.parseDouble().

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

4. Print both converted values.

3. Code Program

public class StringToDoubleExample {
    public static void main(String[] args) {
        // String to be converted
        String doubleString = "3.14159";

        // Convert string to primitive double
        double doublePrimitive = Double.parseDouble(doubleString);

        // Convert string to Double object
        Double doubleObject = Double.valueOf(doubleString);

        // Print the results
        System.out.println("Converted to primitive double: " + doublePrimitive);
        System.out.println("Converted to Double object: " + doubleObject);
    }
}

Output:

Converted to primitive double: 3.14159
Converted to Double object: 3.14159

Explanation:

1. String doubleString = "3.14159": Declares and initializes a string that contains a numerical value which can be converted to a double.

2. double doublePrimitive = Double.parseDouble(doubleString): Converts the string to a primitive double using Double.parseDouble().

3. Double doubleObject = Double.valueOf(doubleString): Converts the string to a Double object using Double.valueOf().

4. System.out.println("Converted to primitive double: " + doublePrimitive) and System.out.println("Converted to Double object: " + doubleObject): Prints both the primitive double and the Double object to the console, verifying that the string has been successfully converted.


Comments