In this article, we are going to explore all the possible ways to convert string to int in Java.

Typically, converting String to Integer or int is a common practice in Java. Especially, when we want to perform mathematical operations.

So, let’s see how we can achieve this conversion…

We have also convered how to convert String to array. Feel free to check the article.

Converting String to Int

Java offers multiple convenient ways to accomplish String to int conversion.

First, we are going to showcase how to do this using Java methods. Then, we will explain how to achieve the same purpose using Guava and Apache Commons libraries.

Using Integer.parseInt()

Integer provides the parseInt() method especially to convert string to int.

parseInt() parses the given String object and returns a signed decimal integer.

Now, let’s see it in action:

    
        String str = "300";
        try {
            int intValue = Integer.parseInt(str);
            System.out.println("My int value is : " + intValue);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    

parseInt() method throws NumberFormatException if the specified string does not contain a parsable integer.

For example, attempting to convert “300Km” will simply lead to NumberFormatException with the following stack trace:

    
        java.lang.NumberFormatException: For input string: "300Km"
            at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
            at java.lang.Integer.parseInt(Integer.java:580)
            at java.lang.Integer.parseInt(Integer.java:615)
            at com.devwithus.stringtoint.StringToInt.main(StringToInt.java:10)
    

So, please bear in mind that the string must contain an int representation. All the string characters must be digits.

However, there is an exception, the first character may be a minus sign ‘-’ or a plus sign ‘+’.

Using Integer.valueOf()

Integer comes with another great method called valueOf(). This method works same as parseInt().

The sole difference is that it returns an Integer instead of int. The returned Integer object holds the int value represented by the given string.

Simarly, valueOf() throws NumberFormatException if the string contains non-digit characters.

Let’s see how we can use valueOf() in practice to achieve string to int conversion:

    
        int valueToAdd = 150;
        String str = "-150";
        try {
            int intFromString = Integer.valueOf(str);
            int sum = intFromString + valueToAdd;
            System.out.println("Sum value is : " + sum);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    

As we can see, we converted a string representation of a negative value to int.

By default, valueOf() return an Integer. However, we can specify int as the return type too, thanks to the unboxing mechanism.

Using Integer.decode()

Integer.decode() is another option to consider when converting string to integer.

Similarly, to the previous methods, decode() accepts a String object as an argument and returns an Integer object holding the int value.

The following example shows how to use Integer.decode() to convert string into int:

    
        int minusValue = 5;
        String str = "50";
        try {
            int intFromString = Integer.decode(str);
            int minusResult = intFromString - minusValue;
            System.out.println("Minus Result is : " + minusResult);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    

As shown above, the method throws the same exception if the given string contains non-digit characters.

For example a String object holding “50CM” as value, would throw an exception.

Using Scanner.nextInt()

Scanner class is a simple text parser that breaks an input into several tokens.

It comes with the nextInt() method that can be used to convert the next token into an int value.

To exemplify the use nextInt(), let’s consider the following code sample:

    
        String s = "500";
        Scanner scanner = new Scanner(s);
        while (scanner.hasNext()) {
            if (scanner.hasNextInt()) {
                int intFromString = scanner.nextInt();
                System.out.println("String to int result :" + intFromString);
            }
        }
        scanner.close();
    

We used hasNextInt() to check if the next token holds a valid int value. This verification allows us to avoid InputMismatchException.

Using Guava

Now that we know how to use Java methods to convert String to int. Let’s see how we can use third-party methods to do the same thing.

First, we are going to demonstrate how to use the Guava library.

Guava provides the Ints.tryParse method to parse the passed string as a signed decimal integer value:

    
        String inputString = "-156";
        int result = Ints.tryParse(inputString);
        System.out.println(result);
    

tryParse accepts ‘-’ as the minus sign. However, it does not recognize ‘+’ as the plus sign.

Please keep in mind that this method returns null when it fails to parse the given string.

Using Apache Commons Lang

Apache Commons Lang is an external library that provides a set of utilities for String and number manipulation. Among these helper classes, we find the NumberUtils.

This class utility comes with a handy static method called toInt:

    
        String givenString = "345";
        int intResult = NumberUtils.toInt(givenString);
        System.out.println(intResult);
    

Unlike other methods, toInt returns the default value instead of throwing an exception if the string to int conversion fails.

Converting a String with Leading Zeros to int

Sometimes, we need to perform arithmetic operations or manipulate numbers with leading zeros.

For example, we may want to add a number to another number with leading zeroes and retain those zeroes.

Let’s see how to convert String with leading zeros to int and perform an addition operation on the conversion result:

    
        int numberToAdd = 100;
        String serialNumber = "000000123";
        int serialInt = Integer.parseInt(serialNumber);
        int serialSum = serialInt+numberToAdd;
        
        String newSerialNumber = String.format("%06d", serialSum);
        System.out.println("New Serial Number: " + newSerialNumber);
    

As we can see, we used Integer.parseInt to convert our string to int. Then, we performed the addition arithmetic operation.

Lastly, we used String.format to format the output with the leading zeros.

Conclusion

To sum it up, we have shed light on how to convert string to int in Java.

Along the way, we have explained how to achieve string to int conversion using Java methods.

Then, we have seen how to accomplish the same purpose using third-party libraries such as Guava and Apache Commons.