Saturday, December 26, 2009

[Java] How To Check if a String is a Valid Number?

If you are someone new to Java and would like to check if a String is a valid number or not, this post will help you get answer to your question.
Below is the coded snippet with explanation for checking out if a string is a valid number. The below mentioned code is written in Java.
In the below mentioned code snippet, i declared an integer called isThisANumber , this integer will be used to save the parsed Integer. Static method parseInt( ) of the Integer class has been used to attempt to convert the string parameter into an Integer. In case if the string is not a valid integer and throws up parsing issues while converting, NumberFormatException is thrown.

int isThisANumber = 0;
try
{
isThisANumber = Integer.parseInt(someStringToTest);
}
catch (NumberFormatException nfe)
{
System.out.println("This string is not a valid number."); //Oops..not a valid int
}
Feedback Form
Feedback Form