Java – Check if String contains only Alphabets
To check if String contains only alphabets in Java, call matches() method on the string object and pass the regular expression "[a-zA-Z]+"
that matches only if the characters in the given string is alphabets (uppercase or lowercase).
String.matches() with argument as "[a-zA-Z]+"
returns a boolean value of true if the String contains only alphabets, else it returns false.
The syntax to use a String.matches() to check if String contains only alphabets is
String.matches("[a-zA-Z]+")
Example – Positive Scenario
In the following program, we will take a string and check if it contains only alphabets using String.matches() method.
Java Program
public class Example {
public static void main(String[] args){
String str = "abcdABCD";
boolean result = str.matches("[a-zA-Z]+");
System.out.println("Original String : " + str);
System.out.println("Does string contain only Alphabets? : " + result);
}
}
Output
Original String : abcdABCD
Does string contain only Alphabets? : true
Example – Negative Scenario
In the following program, we will take a string containing some numbers and whitespace characters. When we check if this String contains only alphabets using String.matches() method, we should get false as return value.
Java Program
public class Example {
public static void main(String[] args){
String str = "abcd ABCD 1234";
boolean result = str.matches("[a-zA-Z]+");
System.out.println("Original String : " + str);
System.out.println("Does string contain only Alphabets? : " + result);
}
}
Output
Original String : abcd ABCD 1234
Does string contain only Alphabets? : false
Conclusion
In this Java Tutorial, we learned how to check if given String contains only alphabets, using String.matches() method.