Java - Double valueOf(String) method
Description
The Java Double valueOf(String s) method returns a Double object holding the double value represented by the argument string s.If s is null, then a NullPointerException is thrown.
Declaration
Following is the declaration for java.lang.Double.valueOf() method
public static Double valueOf(String s) throws NumberFormatException
Parameters
s − This is the string to be parsed.
Return Value
This method returns a Double object holding the value represented by the String argument.
Exception
NumberFormatException − if the string does not contain a parsable number.
Getting Double from a String Example
The following example shows the usage of Double valueOf(String) method to get a Double object from a String. We've created a String with a valid double value and then using valueOf() method, we're retrieving the Double object and printing it.
package com.tutorialspoint;
public class DoubleDemo {
public static void main(String[] args) {
// returns the double value represented by the string argument
String str = "50";
Double retval = Double.valueOf(str);
System.out.println("Value = " + retval);
}
}
Output
Let us compile and run the above program, this will produce the following result −
Value = 50.0
Facing Exception While Getting Double from an Invalid String Example
The following example shows the usage of Double valueOf(String) method to get a Double object from a String. We've created a String with an invalid double value and then using valueOf() method, we're trying to retrieve the Double object and printing it. Program throws an exception as expected.
package com.tutorialspoint;
public class DoubleDemo {
public static void main(String[] args) {
// returns the double value represented by the string argument
String str = "abc";
Double retval = Double.valueOf(str);
System.out.println("Value = " + retval);
}
}
Output
Let us compile and run the above program, this will produce the following result −
Exception in thread "main" java.lang.NumberFormatException: For input string: "abc" at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source) at sun.misc.FloatingDecimal.parseDouble(Unknown Source) at java.lang.Double.parseDouble(Unknown Source) at java.lang.Double.valueOf(Unknown Source) at com.tutorialspoint.DoubleDemo.main(DoubleDemo.java:9)
Getting Double from a Negative String Example
The following example shows the usage of Double valueOf(String) method to get a Double object from a String. We've created a String with a valid negative double value and then using valueOf() method, we're retrieving the Double object and printing it.
package com.tutorialspoint;
public class DoubleDemo {
public static void main(String[] args) {
// returns the double value represented by the string argument
String str = "-50";
Double retval = Double.valueOf(str);
System.out.println("Value = " + retval);
}
}
Output
Let us compile and run the above program, this will produce the following result −
Value = -50.0