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.


/**
 *
 * @author javadb.com
 */

public class Main {
    
    /**
     * This method checks if a String contains only numbers
     */

    public boolean containsOnlyNumbers(String str) {
        
        //It can't contain only numbers if it's null or empty...
        if (str == null || str.length() == 0)
            return false;
        
        for (int i = 0; i < str.length(); i++) {

            //If we find a non-digit character we return false.
            if (!Character.isDigit(str.charAt(i)))
                return false;
        }
        
        return true;
    }

    
    /**
     * @param args the command line arguments
     */

    public static void main(String[] args) {
        Main main = new Main();
        System.out.println(main.containsOnlyNumbers("123456"));
        System.out.println(main.containsOnlyNumbers("123abc456"));
    }
}


The output from the example will be:

true
false

See also: Validate if string is a number

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: