Validate if a String contains only numbers

Often it is necessary to validate input data. One such validation could be to check if a user has entered a sequence of numbers.
This example shows how you can check a String to see if it only contains integers. This validation could be done with less code if we were using regular expressions, but this example aims to keep it simple and more understandable so we use the Character wrapper class instead.
The Character class has a static method called isDigit() which takes a char value as argument and returns true if it’s a number, or else it returns false.
So we loop through the String and pass every character in it to the isDigit() method. If we find a non-digit character, we just halt the loop and return false.

See also: Validate if string is a number

Search for more Java info on this site here:
Custom Search

Please type any questions here.