Strings are widely used in the field of programming to store user-provided and calculated data. The String can be a combination of characters, numbers, or both. When taking data from the user, that data is validated to ensure that user-provided String data contains only characters or a combination of numbers. This is important in ensuring the correctness and integrity of the application.

This guide explains the procedure to check if a String contains Numeric values in Java.

How to Check if a String is Numeric in Java?

The String can be checked for numeric values using several approaches like the “regex expression”, “isDigit()” method, and Stream API methods. Moreover, the user can utilize the methods offered by Apache Commons Lang3 Library like “NumberUtils.isCreatable()” and “StringUtils.isNumeric()”. 

Let’s implement each approach to check if the provided String holds a Numeric value or not. In addition, at the bottom of this guide, the comparison of all methods according to their average execution time is performed. That comparison helps you choose which method is perfect for you.

Method 1: Check if a String is Numeric Using Regex Expression

The regular expressions are different patterns that are set up according to the requirements to match and manipulate text. The String compares with the stored pattern to check whether the String contains the element that matches the pattern or not. This pattern-matching operation is done using the “matches()” method. Let’s apply the regex expression approach to our requirement:

public class StringContainsNumber {

public static void RegexMethod(String input) {
  if (input.matches(".*\\d.*")) {
  System.out.println("The String '" + input + "' Contains Numbers.");
  }
  else {
  System.out.println("No Numbers Found in the '" + input + "' String");
  }
}
public static void main(String[] args) {
  String sampleString = "-Hello456World";
  String sampleString1 = "Wassap";
  String sampleString2 = "";
  String sampleString3 = "   ";
  String sampleString4 = "0.245";
 
  RegexMethod(sampleString);
  RegexMethod(sampleString1);
  RegexMethod(sampleString2);
  RegexMethod(sampleString3);
  RegexMethod(sampleString4);
}
}

The description of the above code is as follows:

  • First, define a method “RegexMethod” accepting the single argument of “input”. Inside it, utilize the “if” statement containing the “matches()” method with the pattern of “.*\\d.*”. This pattern represents all numeric digits ranging from “0 to 9”.
  • Now, display the found or not found messages according to the result obtained from the “matches()” method.
  • Lastly, declare and pass multiple to-be-checked Strings as an argument in the created “RegexMethod()” method.

Output

Method 2: Check if a String is Numeric Using Character.isDigit() Method

The “isDigit()” method allows users to identify the presence of numeric digits inside the string by checking each String Character. This approach is easy to understand in contrast to the “regular expression” approach. Let’s proceed with its code implementation:

public class StringContainsNumber {

public static boolean isDigitMethod(String input) {
  for (char chars : input.toCharArray()) {
  if (Character.isDigit(chars)) {
    return true;
  }
  }
  return false;
}

public static void main(String[] args) {
  String sampleString = "-Hello456World";
  String sampleString1 = "Wassap";
  String sampleString2 = "";
  String sampleString3 = "   ";
  String sampleString4 = "0.245";

  System.out.println("Is '" + sampleString + "' String Contains Numeric Values -> "+ isDigitMethod(sampleString));
  System.out.println("Is '" + sampleString1 + "' String Contains Numeric Values -> "+ isDigitMethod(sampleString1));
  System.out.println("Is '" + sampleString2 + "' String Contains Numeric Values -> "+ isDigitMethod(sampleString2));
  System.out.println("Is '" + sampleString3 + "' String Contains Numeric Values -> "+ isDigitMethod(sampleString3));
  System.out.println("Is '" + sampleString4 + "' String Contains Numeric Values -> "+ isDigitMethod(sampleString4));
}
}

In the above code block:

  • First, define an “isDigitMethod()” method that accepts a single parameter of “input”. 
  • Then, store each character of the String into an Array using the combination of enhanced “for” loop and “toCharArray()” method. 
  • After that, pass each element of an array inside the “Character.isDigit()” method to check the numeric digit’s existence. Also, return the value of “true” in case of existence and “false” otherwise.
  • Lastly, pass the targeted Strings in the custom-created “isDigitMethod()” method to identify the Strings containing Numeric values.

Output

Method 3: Check if a String is Numeric Using Java 8 Stream API

The Java 8 API Stream offers the “anyMatch()” and “alMatch” methods to retrieve results if any or all elements satisfy the provided condition. The condition in our case is the “isDigit” method that returns if any or all characters of the String are Numeric or not, as shown below:

public class StringContainsNumber {

public static void isDigitMethod(String input) {
  if (input.chars().anyMatch(Character::isDigit)) {
  System.out.println("The String '" + input + "' Contains Numbers.");
  }
  else {
  System.out.println("No Numbers Found in the '" + input + "' String");
  }
}

public static void main(String[] args) {
  String sampleString = "-Hello456World";
  String sampleString1 = "Wassap";
  String sampleString2 = "";
  String sampleString3 = "   ";
  String sampleString4 = "0.245";

  isDigitMethod(sampleString);
  isDigitMethod(sampleString1);
  isDigitMethod(sampleString2);
  isDigitMethod(sampleString3);
  isDigitMethod(sampleString4);
}
}

In the above code block:

  • First, define an “isDigitMethod()” method that accepts a single parameter of “input”. Then, select each character of the String using the “chars()” method and apply the “anyMatch()” method.
  • This method applies the “isDigit()” method on all characters and returns “true” if any character is a Numeric digit. Then, use the “if/else” conditional statement to display the corresponding found or not found messages on the console.
  • Lastly, pass the targeted Strings in the custom-created “isDigitMethod()” method to identify the Strings containing Numeric values.

Output

Method 4: Check if a String is Numeric Using the Pattern and Matcher Classes

The “Pattern” and “Matcher” classes of “regex” allow us to perform the regular expression approach but in a more optimized and customized manner. These classes offer the “compile()” and “matcher()” methods respectively to save the provided pattern and compare it with provided String characters:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringContainsNumber {

public static void PatternMatcherMethod(String input) {
  Pattern patternObj = Pattern.compile(".*\\d.*");
  Matcher matcherObj = patternObj.matcher(input);
  boolean checker = matcherObj.matches();

  if (checker) {
  System.out.println("The String '" + input + "' Contains Numbers.");
  }
  else {
  System.out.println("No Numbers Found in the '" + input + "' String");
  }
}
public static void main(String[] args) {
  String sampleString = "-Hello456World";
  String sampleString1 = "Wassap";
  String sampleString2 = "";
  String sampleString3 = "   ";
  String sampleString4 = "0.245";
  System.out.println("Via 'Pattern' and 'Matcher' Methods");
 
  PatternMatcherMethod(sampleString);
  PatternMatcherMethod(sampleString1);
  PatternMatcherMethod(sampleString2);
  PatternMatcherMethod(sampleString3);
  PatternMatcherMethod(sampleString4);
}
}

The above code works like this:

  • First, pass the pattern to select the numeric digits to the “pattern.compile()” method and store the result in the “Pattern” class object. Then, apply the “matcher()” method with this object and pass the targeted String as this method argument.
  • Store the result in a “Matcher” class object and apply the “matches()” method to it. This method returns a result in boolean values indicating the existence or non-existence of numeric values in a String.

Output

Method 5: Check if a String is Numeric Using the replaceAll() Method

Another approach to check the existence of numeric digits in the String is using the combination of “replaceAll()” and “isEmpty()” methods. The “replaceAll()” accepts regular expression and value as the first and second parameters. By using this method, the user can remove all non-numeric digits and then check whether there are any remaining digits or not. If yes, then the String contains numeric digits and vice versa:

public class StringContainsNumber {

public static void replaceAllMethod(String input) {
  String pattern = input.replaceAll("\\D", "");
  boolean checker =  pattern.isEmpty();

  if (!checker) {
  System.out.println("The String '" + input + "' Contains Numbers.");
  }
  else {
  System.out.println("No Numbers Found in the '" + input + "' String");
  }
}

public static void main(String[] args) {
  String sampleString = "-Hello456World";
  String sampleString1 = "Wassup";
  String sampleString2 = "";
  String sampleString3 = "   ";
  String sampleString4 = "0.245";

System.out.println("Via 'replaceAll()' Method:\n");
 
  replaceAllMethod(sampleString);
  replaceAllMethod(sampleString1);
  replaceAllMethod(sampleString2);
  replaceAllMethod(sampleString3);
  replaceAllMethod(sampleString4);
}
}

The above code works like this:

  • First, create a “replaceAllMethod()” method, and inside it apply the “replaceAll()” method over the received parameter. This replaceAll()” method accepts a regular expression selecting all non-numerical digits and replaces them with an empty String.
  • Now, apply the “isEmpty()” method over it received result to identify whether the String contains any value or not. The String will be empty if there are no values and vice versa. 
  • Lastly, print the found or not found message on the console using the “if/else” conditional statements. 

Output:

Method 6: Check if a String is Numeric Using Apache Commons Library

The Apache Commons library offers multiple methods to check the existence of numeric digits inside the provided String. These methods provide the most optimized result while consuming a minimum execution time. These methods are named as:

  • NumberUtils.isCreatable
  • NumberUtils.isParsable
  • StringUtils.isNumeric
  • StringUtils.isNumericSpace

Let’s implement a couple of provided methods in Java.

Check if a String is Numeric Using the “NumberUtils” Class Methods

The “NumberUtils” class offers two methods that help in finding the existence of numeric values inside the String namely “isCreatable()” and “isParsable()”. The “isCreateable()” is considered a better option because of its minimum average compilation time. Moreover, it provides comparatively better results when the data contains lots of numeric digits, decimal digits, or null values. On the other hand, the “isParseable()” method has less average time with both easy and complex data sets.

To use both methods, the user must add the below dependencies inside the “pom.xml” file. This file is auto-created during the creation of a Java “Maven” project:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-math3</artifactId>
    <version>3.6.1</version>
</dependency>

Once added, let’s implement both methods:

public class StringContainsNumber {

public static void main(String[] args) {
  String sampleString = "-Hello456World";
  String sampleString1 = "Wassup";
  String sampleString2 = "65";
  String sampleString3 = "0xA10";
  String sampleString4 = "0.245";

  System.out.println("\nVia 'NumberUtils.isCreatable()' Method:");
  System.out.println("Is '" + sampleString + "' String Contains Numeric Values -> "+ NumberUtils.isCreatable(sampleString));
  System.out.println("Is '" + sampleString1 + "' String Contains Numeric Values -> "+ NumberUtils.isCreatable(sampleString1));
  System.out.println("Is '" + sampleString2 + "' String Contains Numeric Values -> "+ NumberUtils.isCreatable(sampleString2));
  System.out.println("Is '" + sampleString3 + "' String Contains Numeric Values -> "+ NumberUtils.isCreatable(sampleString3));
  System.out.println("Is '" + sampleString4 + "' String Contains Numeric Values -> "+ NumberUtils.isCreatable(sampleString4));

  System.out.println("\nVia 'NumberUtils.isParseable()' Method:");
  System.out.println("Is '" + sampleString + "' String Contains Numeric Values -> "+ NumberUtils.isParsable(sampleString));
  System.out.println("Is '" + sampleString1 + "' String Contains Numeric Values -> "+ NumberUtils.isParsable(sampleString1));
  System.out.println("Is '" + sampleString2 + "' String Contains Numeric Values -> "+ NumberUtils.isParsable(sampleString2));
  System.out.println("Is '" + sampleString3 + "' String Contains Numeric Values -> "+ NumberUtils.isParsable(sampleString3));
  System.out.println("Is '" + sampleString4 + "' String Contains Numeric Values -> "+ NumberUtils.isParsable(sampleString4));
}
}

In the above code block:

  • Inside the “main()” method, different Strings are passed into the “isCreatable()” and “isParseable()” methods. To identify whether the String contains the numeric digits as a value or not. The result of each operation is then displayed on the console. 
  • The “isCreatable()” method also accepts the numeric strings of hexadecimal numbers. So, it returns “true” opposite to the “isParseable()” method due to its limitations.

Output

The below output shows the result obtained by both methods of the “NumberUtils” class:

Check if a String is Numeric Using the “StringUtils” Class Methods

The “StringUtils” offers two methods namely “isNumeric()” and “isNumericSpace()” to check the existence of numeric values in the String. These methods are less flexible and are mostly used to find the negative numeric values or the Unicode representation of numeric digits. 

The “isNumeric()” method extracts the numeric digits from the String and converts them into a corresponding Unicode representation. Once converted, the method will return true or false accordingly. Moreover, it also throws “false” for the negative and decimal numbers.

The “isNumericSpace()” method is an extended or inherited form of the “isNumeric()” method. As an addition, it checks for the empty spaces in the String and between the String characters. It returns “true” if the String contains only empty spaces or if the digits are separated by a space like “6 7”.

Let’s implement both methods in a single Java program for a better working comparison:

public class StringContainsNumber {
public static void main(String[] args) {
  String sampleString = "-Hello456World";
  String sampleString1 = "-67";
  String sampleString2 = "67";
  String sampleString3 = "0xA10";
  String sampleString4 = "0.245";
  String sampleString5 = " ";
 
  System.out.println("\nUsing 'StringUtils.isNumeric()' Method:");
  System.out.println("Is '" + sampleString + "' String Contains Numeric Values -> "+ StringUtils.isNumeric(sampleString));
  System.out.println("Is '" + sampleString1 + "' String Contains Numeric Values -> "+ StringUtils.isNumeric(sampleString1));
  System.out.println("Is '" + sampleString2 + "' String Contains Numeric Values -> "+ StringUtils.isNumeric(sampleString2));
  System.out.println("Is '" + sampleString3 + "' String Contains Numeric Values -> "+ StringUtils.isNumeric(sampleString3));
  System.out.println("Is '" + sampleString4 + "' String Contains Numeric Values -> "+ StringUtils.isNumeric(sampleString4));
  System.out.println("Is '" + sampleString5 + "' String Contains Numeric Values -> "+ StringUtils.isNumeric(sampleString5));
 
  System.out.println("\nUsing 'StringUtils.isNumericSpace()' Method:");
  System.out.println("Is '" + sampleString + "' String Contains Numeric Values -> "+ StringUtils.isNumericSpace(sampleString));
  System.out.println("Is '" + sampleString1 + "' String Contains Numeric Values -> "+ StringUtils.isNumericSpace(sampleString1));
  System.out.println("Is '" + sampleString2 + "' String Contains Numeric Values -> "+ StringUtils.isNumericSpace(sampleString2));
  System.out.println("Is '" + sampleString3 + "' String Contains Numeric Values -> "+ StringUtils.isNumericSpace(sampleString3));
  System.out.println("Is '" + sampleString4 + "' String Contains Numeric Values -> "+ StringUtils.isNumericSpace(sampleString4));
  System.out.println("Is '" + sampleString5 + "' String Contains Numeric Values -> "+ StringUtils.isNumericSpace(sampleString5));
}
}

In the above code block, multiple Strings are created and passed into the “isNumeric()”, and “isNumericSpace()” methods of the “StringUtils” class. The result obtained by invoking each method is then displayed on the console.

Output

The generated output shows the result obtained by the utilization of both methods of the “StringUtils” class:

Which is the Best Method to Check if a String is Numeric in Java?

To find out the best method for identifying the existence of numeric digits in String we have performed the benchmarking. With benchmarking, the average execution time of all methods for simple data sets that do not include too many numbers or decimal values is shown below:

MethodModeExecution Time/ScoreError
RegularExpressionsavgt101.580± 4.244
CoreJavaavgt57.241± 0.792
NumberUtils.isCreatableavgt26.711± 1.110
NumberUtils.isParsableavgt46.577 ± 1.973
StringUtils.isNumericavgt35.885± 1.691
StringUtils.isNumericSpaceavgt31.979± 1.393

Now, the result after increasing the complexity of data sets by including more numeric digits, decimal, and negative values is shown below:

MethodModeExecution Time/ScoreError
RegularExpressionsavgt7168.761± 344.597
CoreJavaavgt10162.872± 798.387
NumberUtils.isCreatableavgt1703.243± 108.244
NumberUtils.isParsableavgt1589.915± 203.052
StringUtils.isNumericavgt1071.753± 8.657
StringUtils.isNumericSpaceavgt1157.722± 24.139

The above benchmarks show that the best methods are the ones provided by Apache Commons Lang. They offer greater flexibility while providing the most optimized result in a minimum execution period. So, one should use these methods to check the existence of numeric digits in a String.

Important: Other than these methods, there exist some other well-known Plain Java methods to check the numeric strings. Read the linked guide to learn more about these methods. 

That’s all about checking the Numeric digits in a String.

Conclusion

There are several approaches to checking the existence of numeric values inside the provided String. These methods are “isDigit()”, “anyMatch()”, “replaceAll()”, “Compile()” and “Matcher()”. The user can also use the following methods namely “NumberUtils.isCreatable()”, “NumberUtils.isParsable()”, “StringUtils.isNumeric()”, and “StringUtils.isNumericSpace()”. These methods are provided by the Apache Commons Lang3 Library and they offer the minimum execution time while maximizing the flexibility.