The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Object Basics and Simple Data Objects

Converting Strings to Numbers

Sometimes, a program ends up with numeric data in a string object—a value entered by the user, for example. The numeric type-wrapper classes ( Byte (in the API reference documentation), Integer (in the API reference documentation), Double (in the API reference documentation), Float (in the API reference documentation), Long (in the API reference documentation), and Short (in the API reference documentation)) each provide a class method named valueOf that converts a string to an object of that type. Here's a small example, ValueOfDemo (in a .java source file) , that gets two strings from the command line, converts them to numbers, and performs arithmetic operations on the values:
public class ValueOfDemo {
    public static void main(String[] args) {

	//this program requires two arguments on the command line
        if (args.length == 2) {

            //convert strings to numbers
            float a = Float.valueOf(args[0]).floatValue();
            float b = Float.valueOf(args[1]).floatValue();

            //do some arithmetic
            System.out.println("a + b = " + (a + b) );
            System.out.println("a - b = " + (a - b) );
            System.out.println("a * b = " + (a * b) );
            System.out.println("a / b = " + (a / b) );
            System.out.println("a % b = " + (a % b) );
        } else {
            System.out.println("This program requires two command-line arguments.");
        }
    }
}
The following is the output from the program when you use 4.5 and 87.2 for the command line arguments:
a + b = 91.7
a - b = -82.7
a * b = 392.4
a / b = 0.0516055
a % b = 4.5

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.