How to convert String to int

In Java we have multiple ways to convert String to int. We will see a few of those ways in this post.

1. Convert String to int using Integer.parseInt()

If the String value doesn’t contain all digits OR if the String value has all digits but exceeds the max limit that can be allowed in an Integer, then during converting String to int, a NumberFormatException is thrown. So you may want to handle this exception when converting String to int.

A String can also be converted to int using a radix specified by public static int parseInt(String s,int radix)
See Examples

In the examples the 2nd param we are passing is the format of String we have received.
10 – regular
16- Hexadecimal
2- Binary

Complete Example
Lets see an example that will use both the methods to convert string to int.

Output

2. Convert String to int using Integer.valueOf()

Similar to Integer.parseInt(), we can convert String to int using Integer.valueOf().
We can also convert the hexadecimals or binary values using Integer.valueOf(String s,int radix)

We will see a small example.

Difference between Integer.parseInt and Integer.valueOf()

Integer.parseInt() returns a primitive int while Integer.valueOf() returns a new Integer() object
Integer.valueOf() internally uses Integer.parseInt(), hence if you want a primitive value you should use Integer.parseInt().

Other methods to Convert String to int

There are many other ways to convert string to int. Few of them are

References

1. Integer API

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn