How to check if a String is numeric in Java ?

To determine if a string is numeric in Java, you can use multiple approaches depending on the specific requirements (e.g., integers, decimals, scientific notation). Below are detailed methods with examples:

1. Using Regular Expressions (Regex)

Use Case: Validate strings representing integers, decimals, or scientific notation.
Pros: Flexible, no exceptions.
Cons: Requires regex knowledge.

Example Code:

public static boolean isNumeric(String str) {
    if (str == null) return false;
    String trimmed = str.trim();
    if (trimmed.isEmpty()) return false;
    // Regex for integers, decimals, or scientific notation
    return trimmed.matches("^[+-]?((\\d+\\.\\d+)|(\\.\\d+)|(\\d+))([eE][+-]?\\d+)?$");
}

Explanation:

  • Regex Breakdown:
  • ^[+-]?: Optional sign.
  • (\\d+\\.\\d+|\\.\\d+|\\d+): Digits with a decimal, decimal with digits, or integer.
  • ([eE][+-]?\\d+)?: Optional scientific notation (e.g., e5, E-3).

Test Cases:

System.out.println(isNumeric("123"));        // true (integer)
System.out.println(isNumeric("-45.6"));      // true (decimal)
System.out.println(isNumeric(".78"));        // true (decimal)
System.out.println(isNumeric("1.2e3"));      // true (scientific)
System.out.println(isNumeric("12a3"));       // false (non-numeric)

2. Using Double.parseDouble() with Exception Handling

Use Case: Check if a string can be parsed as a double.
Pros: Built-in, handles locales.
Cons: Exceptions for control flow (inefficient), allows NaN/Infinity.

Example Code:

public static boolean isNumeric(String str) {
    if (str == null) return false;
    String trimmed = str.trim();
    try {
        Double.parseDouble(trimmed);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}

Explanation:

  • Trims whitespace and attempts to parse as double.
  • Caveats: Returns true for "NaN", "Infinity", and hex strings (e.g., "0x1F").

Test Cases:

System.out.println(isNumeric("123.45"));     // true
System.out.println(isNumeric(" -123 "));     // true (trims whitespace)
System.out.println(isNumeric("NaN"));        // true (may not be desired)

3. Using Scanner

Use Case: Check if a string is a valid int or double.
Pros: Explicit type checking.
Cons: Slower, limited to int/double.

Example Code:

public static boolean isNumeric(String str) {
    if (str == null) return false;
    try (Scanner scanner = new Scanner(str.trim())) {
        return scanner.hasNextInt() || scanner.hasNextDouble();
    }
}

Test Cases:

System.out.println(isNumeric("42"));         // true (integer)
System.out.println(isNumeric("3.14"));       // true (double)
System.out.println(isNumeric("abc"));        // false

4. Using Apache Commons Lang (External Library)

Use Case: Check if a string contains only digits.
Pros: Simple for integers.
Cons: No support for signs/decimals, requires dependency.

Example Code:

<!-- Add to pom.xml for Maven -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>
import org.apache.commons.lang3.StringUtils;

public static boolean isNumeric(String str) {
    return StringUtils.isNumeric(str); // Checks for digits only (no signs/decimals)
}

Test Cases:

System.out.println(isNumeric("123"));        // true
System.out.println(isNumeric("-123"));       // false (sign not allowed)
System.out.println(isNumeric("12.3"));       // false (decimal not allowed)

Summary

MethodUse CaseHandlesNotes
RegexIntegers, decimals, scientific notationFull numeric validationMost flexible, no exceptions.
Double.parseDouble()Quick check for parsable numbersLocale-aware parsingAvoid for performance-critical code.
ScannerCheck for int/doubleExplicit type validationSlower, uses exceptions.
Apache CommonsCheck for digits-only integersBasic integer validationRequires external library.

Final Notes

  • Trim Whitespace: Always trim input strings to avoid whitespace issues.
  • Localization: Use NumberFormat for locale-specific parsing (e.g., commas as decimals).
  • Performance: Regex is efficient for most cases, while exception-based methods (e.g., parseDouble) are slower.

Leave a Reply

Your email address will not be published. Required fields are marked *