Java Double valueOf() example

In this guide, you will learn about the Double valueOf() method in Java programming and how to use it with an example.

1. Double valueOf() Method Overview

Definition:

The valueOf() method of the Java Double class returns a Double instance representing the specified double value or a String containing a double value.

Syntax:

1. Double Double.valueOf(double d) 
2. Double Double.valueOf(String s) throws NumberFormatException

Parameters:

- double d: The value to be represented as a Double instance.

- String s: The string to be converted into a Double instance.

Key Points:

- It provides an optimized, cache-driven method to retrieve a Double instance (potentially reusing previously cached values for specific number ranges).

- The string-based variant of the method can throw a NumberFormatException if the provided string is not a parsable double.

- Useful for converting both primitive double values and string representations of double values into Double objects.

2. Double valueOf() Method Example

public class ValueOfExample {
    public static void main(String[] args) {
        // Using valueOf with double primitive
        double primitiveValue = 123.45;
        Double doubleObject1 = Double.valueOf(primitiveValue);
        System.out.println("Double object from primitive: " + doubleObject1);

        // Using valueOf with string representation
        String stringValue = "456.78";
        Double doubleObject2 = Double.valueOf(stringValue);
        System.out.println("Double object from string: " + doubleObject2);

        // Exception case (uncomment to see the error)
        // String invalidString = "not a number";
        // Double doubleObject3 = Double.valueOf(invalidString);  // Throws NumberFormatException
    }
}

Output:

Double object from primitive: 123.45
Double object from string: 456.78

Explanation:

In the example provided, we first use the valueOf() method to convert a primitive double value, 123.45, into its Double object representation. 

Subsequently, the string representation of a double value, "456.78", is converted into a Double object. 

A commented-out portion demonstrates the exception that arises when attempting to convert an invalid string into a Double object.

Comments