Java Language Parsing Strings to a Numerical Value


Example

String to a primitive numeric type or a numeric wrapper type:

Each numeric wrapper class provides a parseXxx method that converts a String to the corresponding primitive type. The following code converts a String to an int using the Integer.parseInt method:

String string = "59";
int primitive = Integer.parseInteger(string);

To convert to a String to an instance of a numeric wrapper class you can either use an overload of the wrapper classes valueOf method:

String string = "59";
Integer wrapper = Integer.valueOf(string);

or rely on auto boxing (Java 5 and later):

String string = "59";
Integer wrapper = Integer.parseInteger(string);  // 'int' result is autoboxed

The above pattern works for byte, short, int, long, float and double and the corresponding wrapper classes (Byte, Short, Integer, Long, Float and Double).

String to Integer using radix:

String integerAsString = "0101"; // binary representation
int parseInt = Integer.parseInt(integerAsString,2);
Integer valueOfInteger = Integer.valueOf(integerAsString,2);
System.out.println(valueOfInteger); // prints 5 
System.out.println(parseInt); // prints 5 

Exceptions

The unchecked NumberFormatException exception will be thrown if a numeric valueOf(String) or parseXxx(...) method is called for a string that is not an acceptable numeric representation, or that represents a value that is out of range.