[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;
isThisANumber = Integer.parseInt(someStringToTest); 
catch (NumberFormatException nfe)
System.out.println("This string is not a valid number."); //Oops..not a valid int


You can also follow me on Twitter at http://twitter.com/vaibhav1981

Do stay tuned to Technofriends for more, one of the best ways of doing so is by subscribing to our feeds. You can subscribe to Technofriends feed by clicking here.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: