Convert String to int in Java

July 10, 2020 No comments String int Convert

1. Introduction

Convertion from one type to another is a basic and commonly used operation in programming.

In this article we will showcase the several easy ways how to convert a String into an int or Integer in Java.

2. Using Integer.parseInt()

Simple convertion from String object to primitive int variable we can achive using Integer.parseInt() method.

The signature of parseInt() method is given below:

public static int parseInt(String s) throws NumberFormatException

String given on input must contain only decimal digits, except that the first character could be a minus sign '-'. Method returns int or NumberFormatException is throw when given String does not contain a parsable integer.

The following examples show a simple String to int conversions in Java:

String str = "2000";
int num = Integer.parseInt(str);
String strWithMinus = "-2000";
int num = Integer.parseInt(str);
String strThatWillThrowAnException = "12Test";
int num = Integer.parseInt(str); // this will throw NumberFormatException

3. Using Integer.valueOf()

Another method to convert String to Integer in Java is to use the static method valueOf() available on the Integer class.

The signature the valueOf() method is given below:

public static Integer valueOf(String s) throws NumberFormatException

The difference between parseInt() and valueOf() methods is that parseInt() returns a primitive type int and valueOf() returns an Integer object.

The following examples show a simple String to Integer convertions in Java:

String str = "2000";
Integer numObj = Integer.valueOf(str);
String str = "-2000";
Integer numObj = Integer.valueOf(str);
String str = "Te123";
Integer numObj = Integer.valueOf(str); // this will throw NumberFormatException

4. Using Guava

Although it is required to use the build-in Java conversion mechanism, if we really want to we can use an external library like Guava with which we will achieve the same result. This library provides the method Int.tryParse() which returns a null value if input String does not contain a parsable integer.

The following example shows how to use Guava tryParse() method:

String str = "2000";
Integer numObj = Ints.tryParse(str);
String str = "-2000";
Integer numObj = Ints.tryParse(str);
String str = "Test";
Integer numObj = Ints.tryParse(str); // numObj will be null

5. Conclusion

In this article, we showcased multiple ways of converting String to int/Integer in Java. There are several methods to achieve that but we recommended to use simple functions available even in older versions of Java.

As usual, code examples used in this article can be found in the GitHub repository.

{{ message }}

{{ 'Comments are closed.' | trans }}