Java Top

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE

1. Introduction

Converting a String to an int or Integer is a very common operation in Java. In this article, we will show multiple ways of dealing with this issue.

There are a few simple ways to tackle this basic conversion.

2. Integer.parseInt()

One of the main solutions is to use Integer‘s dedicated static method: parseInt(), which returns a primitive int value:

@Test
public void givenString_whenParsingInt_shouldConvertToInt() {
    String givenString = "42";

    int result = Integer.parseInt(givenString);

    assertThat(result).isEqualTo(42);
}

By default, the parseInt() method assumes the given String is a base-10 integer. Additionally, this method accepts another argument to change this default radix. For instance, we can parse binary Strings as follows:

@Test
public void givenBinaryString_whenParsingInt_shouldConvertToInt() {
    String givenString = "101010";

    int result = Integer.parseInt(givenString, 2);

    assertThat(result).isEqualTo(42);
}

Naturally, it's also possible to use this method with any other radix such as 16 (hexadecimal) or 8 (octal).

3. Integer.valueOf()

Another option would be to use the static Integer.valueOf() method, which returns an Integer instance:

@Test
public void givenString_whenCallingIntegerValueOf_shouldConvertToInt() {
    String givenString = "42";

    Integer result = Integer.valueOf(givenString);

    assertThat(result).isEqualTo(new Integer(42));
}

Similarly, the valueOf() method also accepts a custom radix as the second argument:

@Test
public void givenBinaryString_whenCallingIntegerValueOf_shouldConvertToInt() {
    String givenString = "101010";

    Integer result = Integer.valueOf(givenString, 2);

    assertThat(result).isEqualTo(new Integer(42));
}

3.1. Integer Cache

At first glance, it may seem that the valueOf() and parseInt() methods are exactly the same. For the most part, this is true — even the valueOf() method delegates to the parseInt method internally.

However, there is one subtle difference between these two methods: the valueOf() method is using an integer cache internally. This cache would return the same Integer instance for numbers between -128 and 127:

@Test
public void givenString_whenCallingValueOf_shouldCacheSomeValues() {
    for (int i = -128; i <= 127; i++) {
        String value = i + "";
        Integer first = Integer.valueOf(value);
        Integer second = Integer.valueOf(value);

        assertThat(first).isSameAs(second);
    }
}

Therefore, it's highly recommended to use valueOf() instead of parseInt() to extract boxed integers as it may lead to a better overall footprint for our application.

4. Integer‘s Constructor

You could also use Integer‘s constructor:

@Test
public void givenString_whenCallingIntegerConstructor_shouldConvertToInt() {
    String givenString = "42";

    Integer result = new Integer(givenString);

    assertThat(result).isEqualTo(new Integer(42));
}

As of Java 9, this constructor has been deprecated in favor of other static factory methods such as valueOf() or parseInt(). Even before this deprecation, it was rarely appropriate to use this constructor. We should use parseInt() to convert a string to an int primitive or use valueOf() to convert it to an Integer object.

5. Integer.decode()

Also, Integer.decode() works similarly to the Integer.valueOf(), but can also accept different number representations:

@Test
public void givenString_whenCallingIntegerDecode_shouldConvertToInt() {
    String givenString = "42";

    int result = Integer.decode(givenString);

    assertThat(result).isEqualTo(42);
}

6. NumberFormatException

All mentioned above methods throw a NumberFormatException, when encountering unexpected String values. Here you can see an example of such a situation:

@Test(expected = NumberFormatException.class)
public void givenInvalidInput_whenParsingInt_shouldThrow() {
    String givenString = "nan";
    Integer.parseInt(givenString);
}

7. With Guava

Of course, we do not need to stick to the core Java itself. This is how the same thing can be achieved using Guava's Ints.tryParse(), which returns a null value if it cannot parse the input:

@Test
public void givenString_whenTryParse_shouldConvertToInt() {
    String givenString = "42";

    Integer result = Ints.tryParse(givenString);

    assertThat(result).isEqualTo(42);
}

Moreover, the tryParse() method also accepts a second radix argument similar to parseInt() and valueOf().

8. Conclusion

In this article, we have explored multiple ways of converting String instances to int or Integer instances.

All code examples can, of course, be found over on GitHub.

Java bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
Comments are closed on this article!