Parsing Strings to a Numerical Value

suggest change

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Strings:
* Parsing Strings to a Numerical Value

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap