Check if a Java String is Numeric or Alphanumeric


We can make use of regular expressions to know if a string is numeric or alphanumeric in Java.

Let's take a look at some examples.

public class Example {

    public static void main(String[] args) {

        String string1 = "23.00"; // Numeric
        String string2 = "X01201A"; // Alphanumeric
        String string3 = "AXYKZ"; // Alphabetic

        System.out.println("String1 is " + (isNumeric(string1) ? "numeric" : "not numeric") + " and " +
                (isAlphaNumeric(string1) ? "alphanumeric" : "not alphanumeric"));

        System.out.println("String2 is " + (isNumeric(string2) ? "numeric" : "not numeric") + " and " +
                (isAlphaNumeric(string2) ? "alphanumeric" : "not alphanumeric"));

        System.out.println("String3 is " + (isNumeric(string3) ? "numeric" : "not numeric") + " and " +
                (isAlphaNumeric(string3) ? "alphanumeric" : "not alphanumeric"));
    }

    public static boolean isNumeric(String str) {
        return str.matches("-?\\d+(\\.\\d+)?");
    }

    public static boolean isAlphaNumeric(String str) {
        return str.matches("[a-zA-Z0-9]+");
    }
}
Output:

String1 is numeric and not alphanumeric
String2 is not numeric and alphanumeric
String3 is not numeric and alphanumeric

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap