by BehindJava

How to convert a String to an int in Java

Home » java » How to convert a String to an int in Java

In this tutorial we are going to learn about converting a String into a int in Java.

Firstly understand the problem statement with an example i.e., String contains only numbers, and I want to return the number it represents.

For example, given the string “1234” the result should be the number 1234.

Here are the two ways:

Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);

There is a slight difference between these methods:

valueOf returns a new or cached instance of java.lang.Integer parseInt returns primitive int. The same is for all cases: Short.valueOf/parseShort, Long.valueOf/parseLong, etc.

An alternate solution is to use Apache Commons’ NumberUtils:

int num = NumberUtils.toInt("1234");

The Apache utility is nice because if the string is an invalid number format then 0 is always returned. Hence saving you the try catch block.