Convert a String to an Integer in Java

In this post, we will discuss how to convert a string to integer in Java. If the value of specified string is negative i.e. string prefixed with ASCII ‘-‘, the sign should be preserved in the resultant integer.


There are many ways to convert a string to integer in Java –


1. Integer Class

Integer class provides many methods to convert a string to integer. These methods are static and don’t need instantiation before being called and throws a NumberFormatException if the string does not contain a valid integer.


1.1. Integer.parseInt()

Integer class has parseInt() method that parses the string argument and returns primitive int.

Integer class also provides parseUnsignedInt() that only works on unsigned integer.


1.2. Integer.valueOf()

Integer class provides valueOf() method that returns an Integer object that represents the integer value specified by the string.

To return the value of this Integer as an int, we can use intValue() method:


1.3. Integer.decode()

Integer class decode() method can be used to decode a String into an Integer.

To return the value of this Integer as an int, we can use intValue() method:


2. Scanner.nextInt()

Scanner class can parse strings by breaking it into tokens. We can use nextInt() method to get the only token of the input string as an int.

Above approach will fail for strings like "123 34" as Scanner breaks its input into tokens using a delimiter pattern, which is whitespace by default. We can use useDelimiter() function to specify a delimiter that reads complete string as one single token as shown below:

nextInt() throws an InputMismatchException if next token is not a valid integer.


3. Guava

An alternate solution is to use Guava that has Ints.tryParse() method that parses the specified string as a signed decimal integer value. Unlike Integer class static methods, this method returns null instead of throwing an exception if string cannot be parsed as an integer value.


4. Apache Commons Lang

Apache Commons Lang NumberUtils class also provides toInt() that can convert a string to integer.

Like Guava, this method does not throw an exception if string does not contain a parsable integer. It returns 0 instead. We can also define our own default value in optional second argument of the function.

Related Post: Convert integer to String in Java

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of