How to convert a String to int / Integer in Java

When you want to convert a String to int or Integer you can use two simple methods from the Integer class.

To convert a String to primitive int use Integer.parseInt(String s)

String a = "1234";
int x = Integer.parseInt(a);

To convert a String to an instance of Integer use Integer.valueOf(String s)

String a = "1234";
Integer x = Integer.valueOf(a);

To squeeze out some performance when you convert to Integer you can make use of an internal caching mechanism. Instead of directly using Integer.valueOf(String s) you can use Integer.valueOf(int i) in combination with Integer.parseInt(String s).

1
2
String a = "1234";
Integer x = Integer.valueOf(Integer.parseInt(a));

This seems overly redundant but the Integer.valueOf(int i) method features a cache:

If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.
Oracle Integer Class JavaDoc

In newer Java versions the Integer.valueOf(String s) also makes use of this cache but older versions may not. So if you want to be sure to get this extra of performance in old Java environments just use the code from the snippet above.

Leave a Reply

Your email address will not be published. Required fields are marked *