How to convert a Java String to an int

By Alvin J. Alexander, devdaily.com

Here's a little Java code sample that shows how to try to convert a String to an int. In this example, if the conversion works, the variable pageNum will hold the int version of the pageNumString. If the conversion doesn't work a NumberFormatException will be thrown, and you'll need to deal with that.

String pageNumString = "5";
int pageNum = 0;
try
{
  pageNum = Integer.parseInt(pageNumString);
}
catch (NumberFormatException nfe)
{
  // do something with the exception
}

Because pageNumString is 5 this example should work, but if the string was "five" you'll get yourself a real nice exception. :)


devdaily logo