How to convert string to int in Java?

How does one convert a String to an int in Java?

I have a string which contains only numbers (1-4 numbers to be specific), and I want to return the number which it represents. (Actually I have it first as a StringBuffer if that helps somehow.)

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

by using the Integer.ParseInt() we can convert the string value into integer value.


int foo = Integer.parseInt("1234");


See the Javadoc for more information.

For example, here are two ways:

Integer x = Integer.valueOf(str);

// or

int y = Integer.parseInt(str);

There is a slight difference between these methods:


valueOf returns new instance of java.lang.Integer

parseInt returns primitive int.