Skip to content

Check If String is Number in Java

Check if String is number in Java example shows how to check if the string is a number. It also shows how to check if the string is a number using the regex or Double class.

How to check if the string is a number in Java?

There are a couple of ways using which we can check that. You can check this by using the parseDouble method of the Double class. This method parses the input string to a double value and returns it if the string contains a valid number. However, it throws NumberFormatException if the input string contains an invalid numeric value.

We will make use of this simple function to check if the string contains a valid number. Here is the example code that has a method that makes use of that.

Output

As you can see from the output, the method correctly identifies the valid integers, double values, and negative numeric values.

The only problem with this approach is the performance. If you have a very large number of values that need to be checked using this approach, you might suffer some efficiency.

How to check if the string contains a valid number using the regex pattern?

We can do the same check using a regex pattern as well. Here is the pattern that we are going to use.

Where,

Let’s implement this pattern and check the same values again.

Output

As you can see from the output, the regex pattern correctly identified the valid numbers.

If you want to learn more about the regex, please visit the Java Regex tutorial. Also, please visit the Java String tutorial to learn more about string as well.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.