Check if a string contains only alphabets in Java

Given a string, the task is to write a Java program to check whether the string contains only alphabets or not. If so, then print true, otherwise false.

Examples:

Input: GeeksforGeeks
Output: true
Explanation: The given string contains only alphabets so the output is true.

Input: GeeksforGeeks2020
Output: false
Explanation: The given string contains alphabets and numbers so the output is false.

Input: “”
Output: false
Explanation: The given string is empty so the output is false.



 

Method 1: This problem can be solved using the ASCII values. Please refer this article for this approach.

Method 2: This problem can be solved using Lambda expression. Please refer this article for this approach.

Method 3: This problem can be solved using Regular Expression. Please refer this article for this approach.

Method 4: This approach uses the methods of Character class in Java

  • The idea is to iterate over each character of the string and check whether the specified character is a letter or not using Character.isLetter() method
  • If the character is a letter then continue, else return false
  • If we are able to iterate over the whole string, then return true.

Below is the implementation of the above approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

class GFG {
  
    // Function to check if a string
    // contains only alphabets
    public static boolean onlyAlphabets(
      String str, int n)
    {
  
        // Return false if the string
        // has empty or null
        if (str == null || str == "") {
            return false;
        }
  
        // Traverse the string from
        // start to end
        for (int i = 0; i < n; i++) {
            // Check if the specified
            // character is not a letter then
            // return false,
            // else return true
            if (!Character
                .isLetter(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }
  
    // Driver Code
    public static void main(String args[])
    {
        // Given string str
        String str = "GeeksforGeeks";
        int len = str.length();
  
        // Function Call
        System.out.println(
          onlyAlphabets(str, len));
    }
}

chevron_right


Output

true

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.