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

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.

Related posts:

Java Program to Implement Counting Sort
Intersection of Two Lists in Java
Java Program to Implement the Alexander Bogomolny’s UnOrdered Permutation Algorithm for Elements Fro...
Serverless Functions with Spring Cloud Function
Filtering a Stream of Optionals in Java
Using JWT with Spring Security OAuth (legacy stack)
Java Program to Emulate N Dice Roller
Java Deep Learning Essentials - Yusuke Sugomori
Generate Spring Boot REST Client with Swagger
Java Program to Implement Floyd Cycle Algorithm
Java Program to Encode a Message Using Playfair Cipher
Sắp xếp trong Java 8
Understanding Memory Leaks in Java
Java Program to Implement Cartesian Tree
Java Program to Implement Multi-Threaded Version of Binary Search Tree
Java Program to Evaluate an Expression using Stacks
Spring Boot - Bootstrapping
Display Auto-Configuration Report in Spring Boot
Posting with HttpClient
New Features in Java 14
A Guide to TreeMap in Java
Lớp Collectors trong Java 8
Hướng dẫn Java Design Pattern – Proxy
Java CyclicBarrier vs CountDownLatch
Converting Between Byte Arrays and Hexadecimal Strings in Java
Java Program to Check Whether it is Weakly Connected or Strongly Connected for a Directed Graph
Java Program to Generate All Subsets of a Given Set in the Lexico Graphic Order
Java Program to Implement Solovay Strassen Primality Test Algorithm
Hướng dẫn tạo và sử dụng ThreadPool trong Java
Java Program to Implement Coppersmith Freivald’s Algorithm
REST Web service: HTTP Status Code và xử lý ngoại lệ RESTful web service với Jersey 2.x
4 tính chất của lập trình hướng đối tượng trong Java