If the idea is to check only numbers of 0
to 9
, the simplest, fastest and efficient way is:
character >= '0' && character <= '9'
You can create a simple routine like this:
public class NumberUtils {
public static boolean isNumber(char character) {
return character >= '0' && character <= '9';
}
}
And maybe add another routine to check the initial character, like this:
public static boolean startsWithNumber(String s) {
return s != null && !s.isEmpty() && isNumber(s.charAt(0));
}
Other approaches
Character.isDigit
If you look at documentation of the method, will realize that digit is a more general concept than number.
This method will include, for example, Arabic numerals as this: ٢
Integer.parseInt
This method works well, but is only necessary to test a full number and not just a character.
Google Guava
The Guava library has the static method Ints.tryParse(String)
, which basically does the same thing Integer.parseInt
, but without launching exception. If the String is not a number, null
is returned.
However, I repeat that just as the above method is also recommended for full numbers and not just a character.
Regular expression
An effective alternative, but slower, but that is useful especially if there are other types of patterns.
Take an example:
public static boolean startsWithNumber(String s) {
return s != null && s.matches("^\\d.*$");
}
What’s missing is not a
Integer.TryParse
.– user28595
Why the android tag?
– ramaral
@ramaral because I thought it could come in handy to anyone looking for this on android. It is certain that it is a feature of Java whatever it is.
– Jorge B.