java.lang.Double valueOf(String s)

Syntax:

public static Double valueOf(String s) throws NumberFormatException

Java Code Example :

This java example source code demonstrates the use of valueOf(String s) method of Double class.  This method returns the double value of the string method input.

The example evaluates two values from string input and then multiple them to get the result. And then to further check the behavior of the valueOf method, we have asked for the user input for the base and height of a right triangle. From the user input we have calculated the area of the triangle.

package com.javatutorialhq.java.examples;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

/*
 * This example source code demonstrates the use of static method 
 * valueOf(String str) of Double class
 */

public class DoubleValueOfString {

	public static void main(String[] args) {

		String str = "3265.878";
		// get the value in double
		double value = Double.valueOf(str);
		double multiplier = 2.2;
		// multiply value and multiplier
		double result = value + multiplier;
		System.out.println("Result:" + result);

		/*
		 * Example on how to get area of a right triangle 
		 * Get the base and height from user input
		 */

		try {
			System.out.println("\n*******Code to "
					+ "calculate area of triangle******");
			System.out.print("Enter the base:");
			BufferedReader br = new BufferedReader(
					new InputStreamReader(System.in));
			Double base = Double.valueOf(br.readLine());
			System.out.print("Enter the height:");
			br = new BufferedReader(
					new InputStreamReader(System.in));
			double height = Double.valueOf(br.readLine());			
			double areaTriangle = (0.5)*base*height;
			System.out.println("\n******************");
			System.out.println("Area of triangle = " + areaTriangle);
			br.close();

		} catch (NumberFormatException | IOException e) {
			e.printStackTrace();
		}

	}

}

Sample Output :

Running the above example source code will give the following output

Double valueOf(String s) method example

Double valueOf(String s) method example

Suggested Reading List :

References :