How To Check String Content is Digit Only

Sometimes we need to check string has digit only or not for its content. Here are some method than you can use:

1. Using NumberUtils.isDigit(String val)
example:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.commons.lang.math.NumberUtils;

public class Main {
    public static void main(String[]args) throws IOException{  
        String value;
        BufferedReader source = new BufferedReader(new InputStreamReader(System.in));
        try {            
            System.out.println("please input string: ");
            value = source.readLine();
            System.out.println("Is digit only? " + NumberUtils.isDigits(value));            
        } catch (Exception e) {
            System.out.println(e);
        }
    }    
}

2. Using Regex.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.commons.lang.StringUtils;

public class Main {
    public static void main(String[]args) throws IOException{  
        String value;
        BufferedReader source = new BufferedReader(new InputStreamReader(System.in));
        try {            
            System.out.println("please input string: ");
            value = source.readLine();
            System.out.println("Is digit only? " + isDigitOnly(value));            
        } catch (Exception e) {
            System.out.println(e);
        }
    }
    
    private static boolean isDigitOnly(String val){
        if(StringUtils.isEmpty(val)){
            return false;
        }
        return val.matches("\\d+"); //you can use [0-9]+ too
    }
}

Hope this simple article can help 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s