Check if a string contains only alphabets in Java
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
class Main { public static boolean isAlpha(String s) { if (s == null) { return false; } for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (!(c >= 'A' && c <= 'Z') && !(c >= 'a' && c <= 'z')) { return false; } } return true; } public static void main(String[] args) { String s = "ABCD"; System.out.println("IsAlpha: " + isAlpha(s)); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
class Main { public static boolean isAlpha(String s) { return s != null && s.matches("^[a-zA-Z]*$"); } public static void main(String[] args) { String s = "ABCD"; System.out.println("IsAlpha: " + isAlpha(s)); } } |
Output:
IsAlpha: true
If the regex is frequently called, you might want to compile the regex for performance boost:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.regex.Pattern; class Main { private static Pattern p = Pattern.compile("^[a-zA-Z]*$"); public static boolean isAlpha(String s) { return p.matcher(s).find(); } public static void main(String[] args) { String s = "ABCD"; System.out.println("IsAlpha: " + isAlpha(s)); } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
class Main { public static boolean isAlpha(String s) { return s != null && s.chars().allMatch(Character::isLetter); } public static void main(String[] args) { String s = "ABCD"; System.out.println("IsAlpha: " + isAlpha(s)); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 |
import org.apache.commons.lang3.StringUtils; class Main { public static void main(String[] args) { String s = "ABCD"; System.out.println("IsAlpha: " + StringUtils.isAlpha(s)); } } |
That’s all about determining whether a String contains only alphabets in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)