Check if a String Contains only Alphabets in Java
Learn how to check if a string contains only alphabet characters in Java using regular expression . here regular expression [A-Za-z]+ checks whether the string contains only uppercase (A-Z) or lowercase (a-z) letters from start to end.
Code Explanation (Step-by-Step) :
- We take a String variable word containing the input text.
- Create a method named checkAlphabet() to check whether the String contains only alphabets.
- Inside the method, first check that the String is not null and not empty.
- Use the regular expression [A-Za-z]+ with the matches() method to verify that the String contains only uppercase (A-Z) and lowercase (a-z) letters.
- The method returns a boolean value:
-
- true if the String contains only alphabets.
- false otherwise.
- Now Print the returned boolean value as the output.
public class TestAlphabet {
public static void main(String[] args) {
String str = "Welcome";
boolean status = checkAlphabet(str);
System.out.println("String contains only alphabets: " + status);
}
public static boolean checkAlphabet(String str) {
return str != null && !str.isEmpty() && str.matches("[A-Za-z]+");
}
}
Output :-
String contains only alphabets: true
Java Program to Validate Alphabetic Strings
public class TestAlphabet {
public static void main(String[] args) {
String str = "Welcome";
boolean status = checkAlphabet(str);
System.out.println("String contains only alphabets: " + status);
}
public static boolean checkAlphabet(String str) {
if (str == null || str.isEmpty()) {
return false;
}
for (char ch : str.toCharArray()) {
if (!Character.isLetter(ch)) {
return false;
}
}
return true;
}
}
Here are some Java-related programs that will help you understand Java concepts better: