The isNumber() method doesn't exist in Java, but you have several working approaches
Java doesn't have a built-in isNumber() method in the standard library. Instead, you check whether a string or value is a number by using one of three practical approaches: wrapping a parse method in a try-catch block, using regular expressions, or using Apache Commons Lang. Each method works differently depending on what you're checking for — whether you want to accept decimals, negative numbers, or only whole numbers.
The try-catch approach is the most straightforward for most situations. It attempts to convert a string into a number and catches the exception if the conversion fails. This tells you immediately whether the value is a valid number.
Key Takeaways
- The try-catch method wraps Integer.parseInt(), Double.parseDouble(), or Long.parseLong() to test whether a string converts to a number without throwing an exception.
- Regular expressions let you check the format of a string before attempting conversion, and you can customize the pattern to accept decimals, negatives, or only whole numbers.
- Apache Commons Lang provides a NumberUtils.isCreatable() method that handles most number formats in one line, but requires adding an external library to your project.
- The try-catch approach is slower than regex for checking many values in a loop, but it's simpler to read and understand.
- You must decide whether to accept decimals, negative numbers, and leading zeros before choosing your method.
Using try-catch with Integer.parseInt() or Double.parseDouble()
The try-catch approach is the most reliable method because it uses Java's actual parsing logic. You attempt to convert the string to a number, and if it succeeds, the value is a number. If it throws an exception, it isn't.
Here's how to check if a string is a valid integer:
- Write a method that takes a string as input.
- Inside the method, call Integer.parseInt() on the string inside a try block.
- If parseInt() succeeds, return true.
- In the catch block, return false if a NumberFormatException is thrown.
The code looks like this:
public static boolean isNumber(String str) { try { Integer.parseInt(str); return true; } catch (NumberFormatException e) { return false; } }
This method returns true for "42" and "-15", but false for "42.5" or "abc". If you need to accept decimal numbers, use Double.parseDouble() instead of Integer.parseInt(). The same try-catch structure works with any parse method.
Checking for decimals and other number formats
If your input might include decimal numbers like "3.14" or "0.5", use Double.parseDouble() in the same try-catch structure. This accepts both integers and decimals.
public static boolean isNumber(String str) { try { Double.parseDouble(str); return true; } catch (NumberFormatException e) { return false; } }
This returns true for "42", "-15", "3.14", and "0.5", but false for "abc" or "12.34.56". Double.parseDouble() also accepts scientific notation like "1.5e2" (which equals 150), so use this method only if that's what you want.
If you need to reject decimals but accept negative numbers, stick with Integer.parseInt(). If you need to accept only positive whole numbers, add a check after parsing to ensure the value is greater than or equal to zero.
Using regular expressions for pattern matching
Regular expressions let you check the format of a string before attempting to parse it. This is faster when checking many values in a loop, because regex doesn't throw exceptions — it simply matches or doesn't match.
Here's a regex pattern that matches integers (positive and negative):
public static boolean isNumber(String str) { return str.matches("-?\\d+"); }
Breaking down the pattern: -? means an optional minus sign, and \\d+ means one or more digits. This returns true for "42" and "-15", but false for "42.5" or "abc".
For decimal numbers, use this pattern:
public static boolean isNumber(String str) { return str.matches("-?\\d+(\\.\\d+)?"); }
This pattern accepts an optional decimal point followed by one or more digits. It returns true for "42", "-15", and "3.14", but false for "abc" or "12.34.56".
The downside of regex is that it's harder to read if you're not familiar with the syntax. The upside is that it's faster for checking many values, and you can customize the pattern to match almost any number format you need.
Using Apache Commons Lang for a one-line solution
If your project already uses the Apache Commons Lang library, you can use the NumberUtils.isCreatable() method. This handles most common number formats without writing your own logic.
import org.apache.commons.lang3.math.NumberUtils; public static void main(String[] args) { System.out.println(NumberUtils.isCreatable("42")); // true System.out.println(NumberUtils.isCreatable("3.14")); // true System.out.println(NumberUtils.isCreatable("abc")); // false }
NumberUtils.isCreatable() returns true for integers, decimals, negative numbers, and scientific notation. It returns false for non-numeric strings.
The trade-off is that you must add the Apache Commons Lang dependency to your project. If you're already using it for other utilities, this is the simplest choice. If not, the try-catch or regex approaches require no external libraries.
Comparing the three methods side by side
| Method | Speed | Readability | External Library | Best For |
|---|---|---|---|---|
| try-catch with parseInt() | Slower | Very clear | No | Checking a few values, integers only |
| try-catch with parseDouble() | Slower | Very clear | No | Checking a few values, decimals allowed |
| Regular expressions | Faster | Harder to read | No | Checking many values in a loop |
| NumberUtils.isCreatable() | Moderate | Very clear | Yes (Commons Lang) | Projects already using Commons Lang |
For most situations, start with try-catch. It's clear, requires no setup, and works reliably. Switch to regex if you're checking hundreds of values and performance matters. Use NumberUtils only if your project already has the dependency.
Common mistakes to avoid
One common mistake is forgetting to handle null values. If you pass null to Integer.parseInt() or a regex match, your code will crash. Always check for null before testing:
public static boolean isNumber(String str) { if (str == null || str.isEmpty()) { return false; } try { Integer.parseInt(str); return true; } catch (NumberFormatException e) { return false; } }
Another mistake is using the wrong parse method. Integer.parseInt() rejects "3.14", so if your input includes decimals, you must use Double.parseDouble() or a regex pattern that accepts decimals. Test your method with the actual data you expect to receive.
A third mistake is assuming that regex is always faster. For checking a single value or a small batch, try-catch is fine. Regex only wins when you're checking many values repeatedly, because the regex pattern must be compiled each time you call matches() unless you pre-compile it.
Frequently Asked Questions
What's the difference between Integer.parseInt() and Double.parseDouble()?
Integer.parseInt() converts strings to whole numbers only and rejects decimals like "3.14". Double.parseDouble() accepts both whole numbers and decimals. Use Integer.parseInt() if you only want to accept whole numbers, and Double.parseDouble() if decimals are valid input.
Can I check if a value is a number without using try-catch?
Yes. Regular expressions and NumberUtils.isCreatable() both check without throwing exceptions. Regex is faster for many checks, but try-catch is simpler to read. All three approaches work — choose based on your project's needs and what you're already using.
Why does my code crash when I pass null to isNumber()?
Integer.parseInt(null) and regex matching on null both throw exceptions. Always check for null and empty strings before testing. Add a guard clause at the start of your method: if (str == null || str.isEmpty()) return false;
Should I pre-compile my regex pattern if I'm checking many values?
Yes. If you're checking hundreds or thousands of values in a loop, compile the pattern once using Pattern.compile() and reuse it. This avoids recompiling the pattern on every call and makes regex significantly faster than try-catch for large batches.
Does isNumber() work the same way in other programming languages?
No. Python has a built-in isdigit() method. JavaScript has isNaN(). C# has int.TryParse(). Java doesn't have a built-in isNumber() method, so you must use one of the three approaches described here.