Converting String to Int in Java?


In this brief tutorial, we will explain how to convert a string into an integer. We will cover only the case when the string only contains a number. We will cover three ways to convert a string to numbers:

  1. Using parseInt
  2. Using StringBuffer
  3. Using valueOf

Given the string object "9876" the result should be the integer object 9876.

 int foo = Integer.parseInt("9876"); 

The output will be:


Check here for more information about parseInt on the official docs.

If you are using StringBuffer, here is how to do it:


Another alternative is to use the valueOf:

Integer x = Integer.valueOf(str);

The exception NumberFormatException

int foo; 
// The next line will throw exception
String invalidStringInteger = "9876Tutorials";
// The next line will NOT throw exception
String validStringWithInteger = "111"; 

Here are some examples on how to catch the exceptions:

``` java String invalidStringInteger = "9876Tutorials"; try { foo = Integer.parseInt(invalidStringInteger); } catch(NumberFormatException e) { // here code to handle the error }

String validStringWithInteger = "111"; try { foo = Integer.parseInt(validStringWithInteger); } catch (NumberFormatException e) { // code here to handle the error Anything to handle the exception. }

If you want to learn more about the NumberFormatException, check this javadoc.