Convert String to int in java

Posted on Updated on

String and Integer are one of the most use classes in java programming. Developers often have to convert String to Integer and vice-versa while interacting with different APIs. Java provides auto boxing features to convert primitive data type to corresponding classes like int to Integer, double to Double and so on, However, developers need to write their own logic or use third party APIs to convert String to int. Followings are different ways to convert String to int

  1. Using Integer.parseInt(str)
  2. Using Integer.valueOf(str)
  3. Using Apache Commons’NumberUtils

1)  Using Integer.parseInt(str)

The most flexible and easy ways to convert String to int. Integer.parseInt(str) throws NumberFormatException if str parameter passed to the method isn’t a proper number. Below code demonstrate example to convert String to int using Integer.parseInt(str).

Output

2) Using Integer.valueOf(str)

Another way to convert String to int is using Integer.valueOf() method which follows the Factory method design pattern in java. Integer.valueOf() method returns Integer object as a return type which causes logical issue while comparing two objects using == operator. Hence, in case you are using¬†Integer.valueOf(str) method, make sure to use equals method while comparing two objects. It throws NumberFormatException too in case str parameter passed to the method isn’t a proper number. Below code demonstrate example to convert String to int using Integer.valueOf(str).

Output

3) Using Apache Commons’NumberUtils

This is an alternate way to convert String to int. As a java developer I will recommend this utility class to use in enterprise projects. To use NumberUtils, you need to add commons-lang.jar into your projects’ classpath. For Maven add below dependency to pom.xml.

Code to demonstrate example to convert String to int using Apache Commons’NumberUtils.

Output

The Apache utility is a nice solution because in case string isn’t valid number then it will return 0 as a default value. Hence, you don’t need try-catch block. In case you want default value other than 0. You can use NumberUtils.toInt(String str, int defaultValue), in which you can pass default value of your own choice.

Stay tuned for more examples and tutorials !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.