java.lang.Float valueOf(String s)

Float.valueOf in java Overview

The valueOf(String s) java method is used primarily in converting the input String s into Float object. The Float object is a wrapper class for the float primitive data type of java API.

Make a note that the valueOf method of Integer class is static thus it should be accessed statically. Mean to say the we would be calling this method in this format:

Float.valueOf(String s)

Non static method is usually called by just declaring method_name(argument) however in this case since the method is static, it should be called by appending the class name as suffix. We will be encountering a compilation problem if we call the java valueOf method non statically.

Method Syntax

public static Float valueOf(String s) throws NumberFormatException

Method Argument

Data Type Parameter Description
String s the string to be parsed

Method Returns

The valueOf(String s)  method of Float class returns ta Float object holding the value represented by the String argument.

Compatibility

Java 1.0

Discussion

The valueOf(String s) method just parses the String method argument into Float object. One features of the said method is that the leading and trailing white spaces on the method argument is being trimmed/removed.

Java Float valueOf(String s) Example

Below is a simple java example on the usage of valueOf(String s) method of Float class.

package com.javatutorialhq.java.examples;

import java.util.Scanner;

import static java.lang.System.*;

/*
 * This example source code is used to calculate
 * the area of a rectangle making use of
 * valueOf(String s) method of Float class 
 * to get the user input. 
 * 
 */

public class FloatValueOfExample {

	public static void main(String[] args) {
		
		// Ask user input
		System.out.print("Enter height of rectangle:");
		// declare the scanner object
		Scanner scan = new Scanner(System.in);
		// use scanner to get height of a rectangle
		String height = scan.nextLine();
		System.out.print("Enter base of rectangle:");
		//use scanner to get base of a rectangle
		String base = scan.nextLine();
		// close the scanner object
		scan.close();		
		// convert the String input to Float
		Float baseFloat = Float.valueOf(base);
		Float heightFloat = Float.valueOf(height);
		// calculate the area of rectangle
		Float areaRectangle = baseFloat * heightFloat;
		System.out.println("Area of the rectangle is "+areaRectangle);
		
	}

}

Basically on the above example, we just ask for two values (base and height ) as user input on the console as String format. These values as it is in String format and we cannot use it to calculate the area, thus we transformed these values into Float using the valueOf(String s) method before doing the mathematical calculation to get the area.

Sample Output

Below is the sample output when you run the above example.

Float valueOf(String s) Sample Output