This post will discuss several ways in Java to check if a given string contains only alphabets or not. A null string should return false, and an empty string should return true.

1. Plain Java

In plain Java, we can iterate over the characters in the string and check if each character is an alphabet or not. This is demonstrated below:

Download  Run Code

Output:

IsAlpha: true

2. Using Regex

We can use the regex ^[a-zA-Z]*$ to check a string for alphabets. This can be done using the matches() method of the String class, which tells whether the string matches the given regex.

Download  Run Code

Output:

IsAlpha: true

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

Download  Run Code

Output:

IsAlpha: true

3. Using Java 8

From Java 8 onwards, we can efficiently do this with lambda expressions. This is demonstrated below using the isLetter() method of the Character class:

Download  Run Code

Output:

IsAlpha: true

4. Using External Libraries

We can also use the Apache Commons Lang library with the isAlpha() method in the StringUtils class that checks if the string contains only Unicode letters.

Download Code

That’s all about determining whether a String contains only alphabets in Java.