Java – Convert String to int – Detailed guide

May 14, 2016

In most of the cases, the best option to convert String to int in Java is to use the method Integer.parseInt(String):

Let me explain this method below.

Integer.parseInt(String s) method:

The Integer.parseInt(String) method takes a String as a parameter and returns a primitive int value.
If you run the code above, you will get the result like printed below:
The characters of the String passed to this method must be all decimal digits. The only exception is the first character which can be the minus ‘-‘ or the plus ‘+’ character.

 

Integer.parsentInt(String) method signature

You can find below the explanation what kind of parameters the int Integer.parseInt(String string) method takes, what it returns and what exception it can throw.

Parameters Returns Throws
String string int NumberFormatException
The string containing an int to be parsed int value which is the result of parsing The exception which is thrown when the parameter cannot be parsed to int

 

Parsing negative int

Using the Integer.parseInt methods you can parse as well negative values. Look at the example below.

The result of running the above code is:

 

Parsing an int with a plus sign

With the parseInt method, you can parse as well an int with the plus ‘+’ sign at the beginning.

The result of the code above is:

 

 

Parsing not an integer: NumberFormatException

When using the Integer.parseInt(String) you need to pass as a parameter to this method a String which can be parsed to an integer. Let’s try to pass a String as a parameter which is not an integer and see what will be the result.

When you try to run the program you will get the exception:

The exception was thrown because the value 5.1 is not an integer.

 

Parsing a random String: NumberFormatException

You will get a similar error trying to use any other String which is not an integer with the method parseInt. Let’s have a look at the class StringToIntRandomStringParameter:

The result this time is:

 

Click here to add a comment

Leave a comment: