String to int Java

In this article I will shorty explain how to perform conversions between String and numeric types in Java, like String to integer.The mentioned conversions can be easily performed by utilizing toString and parseXXX methods from primitive types’ wrapper classes.

All wrapper classes for numeric types can be found in java.lang package, ie. java.lang.Integer .

Converting integer types

From String to int

String str = "120000";
int num = Integer.parseInt(str);

From int to String

int num = 120000;
String str = Integer.toString(num);


From String to byte

String str = "75";
byte num = Byte.parseByte(str);

From byte to String

byte num = 75;
String str = Byte.toString(num);


From String to short

String str = "16500";
short num = Short.parseShort(str);

From short to String

short num = 16500;
String str = Short.toString(num);


From String to long

String str = "95000000000";
long num = Long.parseLong(str);

From long to String

long num = 95000000000;
String str = Long.toString(num);


From String to float

String str = "123.45";
float num = Float.parseFloat(str);

From float to String

float num = 123.45;
String str = Float.toString(num);


From String to double

String str = "123.45";
double num = Double.parseDouble(str);

From double to String

double num = 123.45;
String str = Double.toString(num);


Important notes

Converting between various data types is not always safe information and may lead to information loss and other issues.

Values out of range

When you are converting String into numeric types, keep in mind that those types have limited range. For example, Byte has maximal value of 127. Trying to parse string with value “128” into byte will result in java.lang.NumberFormatException: Value out of range exception.

Parsing floating-point numbers

Converting String representing a floating-point number must be always parsed into floating-point type. Trying to parse a String with floating-point number into integer type will result in java.lang.NumberFormatException exception.

String str = "3.14";
System.out.println(Float.parseFloat(str));  // -> 3.14
System.out.println(Integer.parseInt(str));  // -> java.lang.NumberFormatException

Learn more about Java