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

<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>30.1.1-jre</version>
</dependency>

// https://mvnrepository.com/artifact/com.google.guava/guava
implementation group: 'com.google.guava', name: 'guava', version: '30.1.1-jre'

Example of Guava Ints

int num2 = Optional.ofNullable("12345")
    .map(Ints::tryParse)
    .orElse(0);

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

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

// https://mvnrepository.com/artifact/org.apache.commons/commons-lang3
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.