Convert String to int or Integer in Java

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);
}

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));
}

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));
}

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);
}

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 in the GitHub repository.

Leave a Reply

Your email address will not be published.