Parsing String to Int in Java

Converting a string number to int in java can be done using several ways. We can use the java Integer class pasrseInt and valueOf methods. We can create of util method to do this with exception handling.

    static int parseInt(String input){
        int result;
        try {
            result = Integer.parseInt(input);
        catch (NumberFormatException e)
            result = 0;
        return result;

Integer num = Integer.valueOf(input);
// or
int num = Integer.parseInt(input);
There is a slight difference between these methods: valueOf returns a new or cached instance of Integer, while parseInt returns primitive int.

Alternate methods using Guava and Apache commons lib

You can use Ints method of Guava library, which in combination with Java 8’s Optional, makes for a powerful and concise way to convert a string into an int with default value in case of null or exception.

You can easily import Guava core lib in your project using gradle or maven build

<!-- -->

implementation group: '', name: 'guava', version: '30.1.1-jre'

Example of Guava Ints

int num2 = Optional.ofNullable("12345")

Apache commons-lang library provides NumberUtils class for parsing strings and doing other number-related operations. This can be included in a project using Gradle or maven as given below

<!-- -->

implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.12.0'

We can use this as given beow

int num1 = NumberUtils.toInt("12345", 0);

the second parameter is the default value in case of parsing exception of input.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.