This post will check if a string starts with a number or not in Java.

1. Naive solution

A naive solution is to extract the first character from the given string using the charAt() method and validate that character falls under the numeric ASCII range or not.

Download  Run Code

2. Using Character.isDigit() method

The recommended solution is to use the Character.isDigit(char) method to check if the first character of the string is a digit or not. Note that this also supports all Unicode digits.

Download  Run Code

3. Using Regex

Another plausible way of determining whether a string ends with a number or not is using regex. This approach is not recommended as regular expressions are extremely slow.

Download  Run Code

 
Note that all the above solutions assume that the string is not empty. If the string is empty, the program will throw a StringIndexOutOfBoundsException.

That’s all about checking if a string starts with a number in Java.