Few Java examples to show you how to check if a String is numeric.

1. Character.isDigit()

Convert a String into a char array and check it with Character.isDigit()

NumericExample.java

package com.favtuts.string;

public class NumericExample {
    public static void main(String[] args) {

        System.out.println(isNumeric(""));          // false
        System.out.println(isNumeric(" "));         // false
        System.out.println(isNumeric(null));        // false
        System.out.println(isNumeric("1,200"));     // false
        System.out.println(isNumeric("1"));         // true
        System.out.println(isNumeric("200"));       // true
        System.out.println(isNumeric("3000.00"));   // false

    }

    public static boolean isNumeric(final String str) {

        // null or empty
        if (str == null || str.length() == 0) {
            return false;
        }

        for (char c : str.toCharArray()) {
            if (!Character.isDigit(c)) {
                return false;
            }
        }

        return true;
    }
}

Output


false
false
false
false
true
true
false

2. Java 8

This is much simpler now.

public static boolean isNumeric(final String str) {

        // null or empty
        if (str == null || str.length() == 0) {
            return false;
        }

        return str.chars().allMatch(Character::isDigit);

    }

3. Apache Commons Lang

If Apache Commons Lang is present in the classpath, try NumberUtils.isDigits()

pom.xml

	<dependency>
		<groupId>org.apache.commons</groupId>
		<artifactId>commons-lang3</artifactId>
		<version>3.9</version>
	</dependency>
import org.apache.commons.lang3.math.NumberUtils;

	public static boolean isNumeric(final String str) {

        return NumberUtils.isDigits(str);

    }

4. NumberFormatException

This solution is working, but not recommend, performance issue.

    public static boolean isNumeric2(final String str) {

        if (str == null || str.length() == 0) {
            return false;
        }

        try {

            Integer.parseInt(str);
            return true;

        } catch (NumberFormatException e) {
            return false;
        }
    }

Download Source Code

$ git clone https://github.com/favtuts/java-core-tutorials-examples

$ cd java-string

References

Leave a Reply

Your email address will not be published. Required fields are marked *