Java Language Converting to and from Strings Parsing Strings to a Numerical Value

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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.



Got any Java Language Question?