Convert String To int – Java

Here’s an example of converting a String to an int primitive using Integer.parseInt()

Here’s a unit test for converting a String to an int in java

Output

Heres an example of converting a String to an Integer object using Integer.valueOf()

Here’s a unit test for converting a String to an Integer object in java

Output

Exceptions

NumberFormatException

Both Integer.parseInt() and Integer.valueOf(number) will throw a NumberFormatException if the String isnt in the correct format for conversion to a number

Here’s a junit test as an example

And heres the stacktrace with the NumberFormatException

References

The Integer class provides methods for converting an int to a String and a String to an int, and other methods for dealing with int

  1. Integer
  2. Integer.parseInt() JavaDoc
  3. Integer.valueOf() JavaDoc
  4. NumberFormatException JavaDoc


Leave a Comment

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