Java
String Manipulation
Programming
Numeric Validation
Coding Tips

How to check if a String is numeric in Java

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In Java, determining if a string is numeric involves assessing whether it consists solely of numbers, potentially including decimal points or negative signs. This check is essential for ensuring that the input is suitable for numeric operations without encountering exceptions. This article will explore various methods to achieve this, the intricacies of each approach, and when to use them.

Method 1: Using Regular Expressions

Regular expressions (regex) provide a powerful way to check if a string adheres to a specific pattern. To determine if a string is numeric, you might use a regex that matches only digits, optional negative signs, and decimal points.

Example Code:

java
public static boolean isNumericRegex(String str) {
    return str.matches("-?\\d+(\\.\\d+)?");
}

Explanation:

  • ^: Asserts the start of a line.
  • -?: Matches zero or one negative sign.
  • \\d+: Matches one or more digits.
  • (\\.\\d+)?: Matches zero or one group of a decimal point followed by one or more digits.
  • $: Asserts the end of a line.

Method 2: Using Apache Commons Lang

If you are already using the Apache Commons Lang library in your project, you can use the NumberUtils.isCreatable() method, which checks more comprehensively whether a String is a valid Java number.

Example Code:

java
1import org.apache.commons.lang3.math.NumberUtils;
2
3public static boolean isNumericApache(String str) {
4    return NumberUtils.isCreatable(str);
5}

Method 3: Java 8 Stream API

For those preferring a more functional style without external libraries, the Java 8 Stream API can be used.

Example Code:

java
public static boolean isNumericStream(String str) {
    return str.chars().allMatch(Character::isDigit);
}

Explanation:

  • str.chars(): Returns an IntStream representing the characters of the string.
  • .allMatch(Character::isDigit): Checks if all characters in the stream are digits.

Method 4: Try-Catch with Parsing

A straightforward approach to check for a numeric string is trying to parse it. If parsing throws a NumberFormatException, the string is not numeric.

Example Code:

java
1public static boolean isNumericParse(String str) {
2    try {
3        Double.parseDouble(str);
4        return true;
5    } catch (NumberFormatException e) {
6        return false;
7    }
8}

Summary Table

MethodDescriptionProsCons
RegexUse regular expressions to match numeric patterns.Precise control over format.Can be complex and slower for large texts.
Apache Commons LangLeverage an external library to check numeric strings.Comprehensive and reliable.Requires external dependency.
Java 8 Stream APIUse modern functional programming techniques.No external dependencies; purely Java 8+.Only straightforward digit checks without negative or decimal handling.
Try-Catch ParsingAttempt to parse the string as a number.Simple and effective for valid number formats.Exception handling can be expensive for performance.

Additional Considerations

  1. Performance: If performance is crucial, consider the overhead of regex and exception handling. Pre-check conditions (like string empty checks) can optimize performance.
  2. Locale-Specific Formats: Numbers can be represented differently across locales (e.g., 1,234.56 in US vs 1.234,56 in Germany). Be mindful of these if internationalization is applicable.
  3. Edge Cases: Always test edge cases like empty strings, very long numbers, or unusual numeric formats to ensure robust application behavior.

By carefully selecting the appropriate method based on the specific requirements of your application, you can effectively determine whether a string is numeric in Java.


Course illustration
Course illustration

All Rights Reserved.