Java – Convert String to an Integer

In this post I will show you, how to convert string to an integer using java. This is useful when you are receiving a number as a string i.e. input from a text field.

Convert String to an Integer Examples:

Example 1: Using Integer.parseInt()

Example 2: Using Integer.valueOf()

Alternatively another approach is to use the valueOf() method, on the Integer class.

Both of the above examples throw a NumberFormatException. You can handle the thrown exception or another option is to use the Guava library which will return null if it cannot parse the input.

Example 3: Using Guava’s Ints.tryParse()

In order to use the Guava library you will need to add the Guava dependancy to your project which can be foundĀ here

Especially relevant consult the official java documentation for more in-depth details which can be found hereĀ here.

I hope you found this post useful, and that it helps with your development.

Similar posts:

  1. Java String basics
  2. How to convert a byte array to string
  3. How to convert an InputStream to a String

Leave a Reply