I realize this is an old question, but I consider it still relevant today.
Although the String matching solution is the most elegant one (at least in my opinion), it is far from being performant. So, if you plan to use this method at scale, you might consider alternative implementations.
I wrote a few short classes for comparing the run times of various implementations. For each implementation, I ran 100 million iterations, half with an all-numeric input (so the method returns true
) and half with letters (so the method returns false
) and following are the results of the runs on my machine.
Alternatives
String matching solution
text.matches("\\d*");
Total runtime: 19206 ms
Pattern matching solution
Similar to the String matching solution, but with better running time because pattern compilation is done only once:
PATTERN.matcher(text).matches();
where PATTERN is defined only once as such: final Pattern PATTERN = Pattern.compile("\\d*");
Total runtime: 9193 ms
IntStream solution
Less concise than the matching solutions, but faster:
text.isEmpty() || IntStream.range(0, text.length()).allMatch(i -> Character.isDigit(text.charAt(i)));
Total runtime: 5568 ms
Simple loop solution
Using the same concept as the IntStream solution, but more verbose:
boolean allDigits = true;
if (!text.isEmpty()) {
for (int i = 0; i < text.length(); i++) {
if (!Character.isDigit(text.charAt(i))) {
allDigits = false;
break;
}
}
}
return allDigits;
Total runtime: 235 ms
Commons lang solution
There is also the commons lang solution which doesn't require you to write any code, but to depend on an external library instead:
StringUtils.isNumeric(text);
Total runtime: 1433 ms
Conclusion
What this test shows is that - leaving aside the external dependency solution - the more elegant the code, the less performant it is, with the most "primitive" solution being also the fastest running one.
That being said, I'm an advocate of clean code, so if you only need to call this method a few times, definitely go for one of the more elegant solutions; in many cases code quality is more important than performance. However, if you know you will be calling it a lot or if it's going to be part of a library, consider going for one of the less elegant but more performant solutions.