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);
System.out.println(i);
}catch(Exception ex) {
System.out.println(ex.getMessage());
}

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…

Advertisements

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