Convert String to Integer
Given a String containing a valid number, the following code bit transforms it into a Integer.
String stringNumber = "1234";
int number = Integer.parseInt(stringNumber);
Explanation
Converting different data types is a very common task in programming.
The class Integer
is one of the wrapper types in Java contained in the java.lang
package, along with Byte
, Short
, Long
, Float
, Double
, Boolean
and Character
. The goal of these classes is to hold the respective primitive type internally, for example, a Character
object will hold a primitive char
, and so on. For this reason, these classes are known as wrapper classes.
Java has built-in features to convert primitives and wrapper classes of the same type automatically. Wrapper classes will provide additional functionally, such as methods and helper operations. Furthermore, wrapper classes can be used with collections, such as Lists, Sets and others.
List<Integer> list = new ArrayList<>();
list.add(10);
// ...
In order to use the method parseInt
from the wrapper class Integer
to convert String
to number, it is required to have a valid integer. The first digit in the String
can represent a minus sign (-
) if required. In case an invalid format is provided, the method will throw the NumberFormatException
error, indicating that given value is not parseable. This is useful for verification purposes too, where one may want to check if the number is valid or not, as per the example below.
public boolean isNumeric(String stringNumber) {
try {
Integer.parseInt(stringNumber);
return true;
} catch (NumberFormatException e) {
return false;
}
}
This was a quick explanation of wrapper types and the use of Integer.parseInt
, which is applied to convert String
to Integer
. Check other entries for more information!