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.
Simple convertion from String object to primitive int variable we can achive using Integer.parseInt() method.
The signature of parseInt() method is given below:
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:
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:
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:
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:
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.