Converting Strings to Numbers

When processing user input it is often necessary to convert a String that the user enters into an int. The syntax is straightforward. It requires using the static Integer.valueOf(String s) and intValue() methods from the java.lang.Integer class. To convert the String "22" into the int 22 you would write

int i = Integer.valueOf("22").intValue();

Doubles, floats and longs are converted similarly. To convert a String like "22" into the long value 22 you would write

long l = Long.valueOf("22").longValue();

To convert "22.5" into a float or a double you would write:

double x = Double.valueOf("22.5").doubleValue();
float y = Float.valueOf("22.5").floatValue();

The various valueOf() methods are relatively intelligent and can handle plus and minus signs, exponents, and most other common number formats. However if you pass one something completely non-numeric like "pretty in pink," it will throw a NumberFormatException. You haven't learned how to handle exceptions yet, so try to avoid passing theses methods non-numeric data.

You can now rewrite the E = mc2 program to accept the mass in kilograms as user input from the command line. Many of the exercises will be similar.

class Energy {
  public static void main (String args[]) {

    double c = 2.998E8;  // meters/second
    double mass = Double.valueOf(args[0]).doubleValue(); 
    double E = mass * c * c;
    System.out.println(E + " Joules");

Here's the output:

$ javac
$ java Energy 0.0456
4.09853e+15 Joules

Previous | Next | Top | Cafe au Lait

Copyright 1997, 2002 Elliotte Rusty Harold
Last Modified February 8, 2002