A Java String to int conversion example

Here's a little Java code sample that shows how to try to perform a Java String to int conversion. 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
{
  // perform the string to int conversion here
  pageNum = Integer.parseInt(pageNumString);
}
catch (NumberFormatException nfe)
{
  // do something with the exception
}

Because pageNumString is 5, this particular String to int conversion will work, but if the string was "five" you'll get yourself a real nice exception. :)

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.