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
truefor"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
| Method | Use Case | Handles | Notes |
|---|---|---|---|
| Regex | Integers, decimals, scientific notation | Full numeric validation | Most flexible, no exceptions. |
| Double.parseDouble() | Quick check for parsable numbers | Locale-aware parsing | Avoid for performance-critical code. |
| Scanner | Check for int/double | Explicit type validation | Slower, uses exceptions. |
| Apache Commons | Check for digits-only integers | Basic integer validation | Requires external library. |
Final Notes
- Trim Whitespace: Always trim input strings to avoid whitespace issues.
- Localization: Use
NumberFormatfor locale-specific parsing (e.g., commas as decimals). - Performance: Regex is efficient for most cases, while exception-based methods (e.g.,
parseDouble) are slower.