Check if String is Number in Java

Some times we want to check if string is number(integer), actually whether String contains only numbers but without try..catch() statement. We can handle it with Regular Expression in Java.

Here is example with try…catch statement:

String numbstr = "12345";

try {
int i = Integer.parseInt(numbstr);
}catch(Exception ex) {

Here is example with RegExp:

String numbstr = "12345";
 if(numbstr.matches("[-0-9]\\d+")) System.out.println(Integer.parseInt(numbstr));

RegularExpression is very fast if you want search some specific characters, words etc…


Leave a Reply

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

You are commenting using your 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