By Alvin Alexander. Last updated: June 4, 2016
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. :)