Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll explore different ways to encapsulate a method to convert String input to an int in Java while handling exceptions elegantly.

2. Problem Statement

The Integer.parseInt() method is commonly used to perform the conversion of a String to an int, but it throws an exception if the input is not a number.

Handling this exception using a try-catch block can make the code repetitive and unreadable:

try {
    return Integer.parseInt(input);
} catch (NumberFormatException e) {
    logger.error("Encountered an exception while converting string to int");
}

Instead, we can encapsulate the conversion in a method that handles the exception and returns a suitable value in case of an error. This also provides ease of modification or update of the error-handling logic in the future.

Now let’s explore some of the ways to achieve this encapsulation.

3. Converting via Encapsulation

In this section, we’ll explore a few approaches to encapsulate the String to int conversion logic. We can use Optional to encapsulate the Integer value that results from the String-to-int conversion or to indicate that the conversion failed:

3.1. Using Integer.parseInt()

We can use the parseInt() method provided by the Integer class to convert a String value to an int. A try-catch block can handle all exceptions, mainly NumberFormatException, and return a default value in the case of an error:

Optional<Integer> convertStringToIntUsingIntegerParseInt(String input) {
    try {
        return Optional.of(Integer.parseInt(input));
    } catch (NumberFormatException e) {
        return Optional.empty();
    }
}

This method uses autoboxing to convert the primitive type int to its corresponding wrapper class, Integer.

3.2. Using Integer.valueOf()

In Java, the valueOf() method is a static method that’s available on certain classes, including String, Integer, Double, and others. It’s used to convert a String representation of a value into an object of the corresponding class.

It internally calls parseInt() if used on an Integer wrapper class. We can use this method to achieve the conversion and handle the error in a single encapsulated method:

Optional<Integer> convertStringToIntUsingIntegerValueOf(String input) {
    try {
        return Optional.of(Integer.valueOf(input));
    } catch (NumberFormatException e) {
        return Optional.empty();
    }
}

3.3. Using Integer.decode()

Integer.decode() works similarly to Integer.valueOf(), but can also accept some other number representations like decimal, hexadecimal, and octal numbers:

Optional<Integer> convertStringToIntUsingIntegerDecode(String input) {
    try {
        return Optional.of(Integer.decode(input));
    } catch (Exception e) {
        return Optional.empty();
    }
}

3.4. Using Apache Commons’ NumberUtils

We can use the Integer conversion method provided by the NumberUtils class in the Apache Commons Lang 3 library. To use the library, we can add a dependency in our pom.xml file:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version>
</dependency>

It accepts a default value to return in case the conversion fails. We can use the toInt() method to achieve our encapsulation:

int convertIntToStringUsingNumberUtils(String input, Integer defaultValue) {
    return NumberUtils.toInt(input, defaultValue);
}

4. Conclusion

In this article, we looked at various approaches for converting a String to an int, handling errors, and dealing with situations where default values need to be returned or errors need to be logged.

As always, the code is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.