O'Reilly logo

Java™ Phrasebook by Timothy Fisher

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Checking Whether a String Is a Valid Number

try {
											int result = Integer.parseInt(aString);
											}
											catch (NumberFormatException ex) {
											System.out.println(
											"The string does not contain a valid
											number.");
											}

In this phrase, we use the parseInt() static method of the Integer class to attempt to convert the string parameter into an integer. If the string parameter cannot be converted into a valid integer, the NumberFormatException is thrown. Therefore, if we do not get a NumberFormatException, we can safely assume that the parseInt() method was able to parse the string into an integer value.

You may want to consider declaring the int variable outside of the try block so that if the NumberFormatException is thrown, you can assign a default value to the variable ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required