Signup/Sign In
LAST UPDATED: OCTOBER 15, 2020

Java Double valueOf(String s) Method

Java valueOf(String s) method is a part of the Double class of the java.lang package. This method is used to return the equivalent Double-object of the string value passed as an argument. It must be noted that the value returned by this method can be interpreted as new Double(Double.parseDouble(s)).

Syntax:

public static Double valueOf(String s) throws NumberFormatException

Parameters:

The parameter passed is the string whose equivalent Double-object is to be returned.

Exception:

NumberFormatException: This exception occurs when the input string is not parsable.

Returns:

Returns the Double-object of the String value passed as parameter.

Example 1:

Here, the Double-object representations are returned of the String value passed.

import java.lang.Double;
public class StudyTonight 
{    
    public static void main(String[] args)
     {  
          String s1 = "909.89";
          String s2 = "-253.67";
          String s3 = "NaN";          
          
          System.out.println("Equivalent Double object Value = " + Double.valueOf(s1));//returns a Double object representing the String specified 
          System.out.println("Equivalent Double object Value = " + Double.valueOf(s2));   
          System.out.println("Equivalent Double object Value = " + Double.valueOf(s3));             
     }  
} 


Equivalent Double object Value = 909.89
Equivalent Double object Value = -253.67
Equivalent Double object Value = NaN

Example 2:

Here is a user-defined example where anyone using this code can put a value of his choice and get the equivalent output.

import java.lang.Double;
import java.util.Scanner;
public class StudyTonight 
{    
    public static void main(String[] args)
    {    
          try
          {
             System.out.println("Enter the string value");
             Scanner sc=new Scanner(System.in);
             String x = sc.next();
             System.out.println("Equivalent Double object Value = " + Double.valueOf(x));//returns a Double object representing the string specified 
           }
           catch(NumberFormatException e)
           {
             System.out.println("Invalid input!!");
           }                  
    }  
} 


Enter the string value
56.87
Equivalent Double object Value = 56.87
*******************************************
Enter the string value
NaN
Equivalent Double object Value = NaN
*******************************************
Enter the string value
0x668
Invalid input!!

Live Example:

Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.



About the author:
A Computer Science and Engineering Graduate(2016-2020) from JSSATE Noida. JAVA is Love. Sincerely Followed Sachin Tendulkar as a child, M S Dhoni as a teenager, and Virat Kohli as an adult.