This post will explore different ways to check if a string contains alphanumeric characters in Java. In other words, determine whether a string consists of only numbers and alphabets. A null string should return false, and an empty string should return true.

Java did not provide any standard method for this simple task. Nevertheless, there are several methods to detect if the given string is alphanumeric in Java:

1. Using Regular Expression

The idea is to use the regular expression ^[a-zA-Z0-9]*$, which checks the string for alphanumeric characters. This can be done using the matches() method of the String class, which tells whether this string matches the given regular expression.

Download  Run Code

Output:

IsAlphaNumeric: true

 
If the regular expression is frequently called, you might want to compile the regular expression for performance boost:

Download  Run Code

Output:

IsAlphaNumeric: true

2. Using Lambda Expressions

From Java 8 onwards, this can be efficiently done using lambda expressions:

Download  Run Code

Output:

IsAlphaNumeric: true

3. Using External Libraries

We can use the Apache Commons Lang library, a method called isAlphanumeric() included in the StringUtils class.

Download Code

4. Naive Solution

In plain Java, we can iterate over the string characters and check each character to be alphanumeric using Character.isLetterOrDigit(char). This is demonstrated below:

Download  Run Code

Output:

IsAlphaNumeric: true

That’s all about determining whether a String contains alphanumeric characters in Java.