The Wayback Machine - https://web.archive.org/web/20240622225909/https://www.geeksforgeeks.org/check-if-a-string-contains-only-alphabets-in-java/
Open In App

Check if a string contains only alphabets in Java

Last Updated : 02 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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




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));
    }
}


Output

true

Time Complexity: O(N), where N is the size of the given string.
Auxiliary Space: O(1), no extra space required so it is a constant.

Method 5 : Using contains() method and ArrayList

Java




import java.util.*;
import java.lang.*;
class Main{
    // 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;
        }
        ArrayList<Character> alphabets = new ArrayList<Character>();
        String alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        for(int i=0;i<alpha.length();i++)
        {
            alphabets.add(alpha.charAt(i));
        }
        // 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 (!alphabets.contains(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));
    }
}


Output

true


Similar Reads

Check if a String Contains Only Alphabets in Java Using Lambda Expression
Lambda expressions basically express instances of functional interfaces (An interface with a single abstract method is called functional interface. An example is java.lang.Runnable). lambda expressions implement the only abstract function and therefore implement functional interfaces. Given a String, we just need to iterate over characters again th
3 min read
Check if a String Contains only Alphabets in Java using Regex
Regular Expressions or Regex is an API for defining String patterns that can be used for searching, manipulating, and editing a text. It is widely used to define a constraint on strings such as a password. Regular Expressions are provided under java.util.regex package. For any string, here the task is to check whether a string contains only alphabe
2 min read
Check if a String Contains Only Alphabets in Java using ASCII Values
Given a string, now we all know that the task is to check whether a string contains only alphabets. Now we will be iterating character by character and checking the corresponding ASCII value attached to it. If not found means there is some other character other than "a-z" or "A-Z". If we traverse the whole string and land up on finding all characte
4 min read
Count of ways to rearrange N digits and M alphabets keeping all alphabets together
Given two positive integers N and M representing the count of distinct digits and alphabets respectively in a string, the task to count the number of ways to rearrange the characters of the string such that all the alphabets are adjacent. Examples: Input: N = 2, M = 2Output: 12Explanation: Possible ways to rearrange characters of a string such that
9 min read
Sub-string that contains all lowercase alphabets after performing the given operation
Given a string str containing lower case alphabets and character '?'. The task is to check if it is possible to make str good or not.A string is called good if it contains a sub-string of length 26 which has every character of lower case alphabets in it. The task is to check if it is possible to make the string good by replacing '?' characters with
15 min read
Program to check if a String in Java contains only whitespaces
Given a string str, the task is to check if this string contains only whitespaces or some text, in Java. Examples: Input: str = " " Output: True Input: str = "GFG" Output: False Approach: Get the String to be checked in str We can use the trim() method of String class to remove the leading whitespaces in the string. Syntax: str.trim() Then we can u
2 min read
How to check if string contains only digits in Java
Given string str, the task is to write a Java program to check whether a string contains only digits or not. If so, then print true, otherwise false. Examples: Input: str = "1234" Output: true Explanation: The given string contains only digits so that output is true. Input: str = "GeeksforGeeks2020" Output: false Explanation: The given string conta
4 min read
How to Check if a String contains only ASCII in Java?
The full form of ASCII is the American Standard Code for Information Interchange. It is the numeric representation of Character. As Java supports multiple languages, and it follows the Unicode system. In simple terms for better understanding, it converts the Character to a specific unique number, and then the number converts to the machine-level co
3 min read
How to Check if a String Contains Only Lowercase Letters in Java?
A string is a data structure that contains a set of characters. It can be a word or can be a sentence. Also, it can be empty or can have a single letter. A string can contain Uppercase letters, Lowercase letters, or numbers of special characters. In this article, we will learn how to check if a String contains only lowercase letters in Java. Approa
4 min read
Check if an array contains only one distinct element
Given an array arr[] of size N, the task is to check if the array contains only one distinct element or not. If it contains only one distinct element then print “Yes”, otherwise print “No”. Examples: Input: arr[] = {3, 3, 4, 3, 3} Output: No Explanation: There are 2 distinct elements present in the array {3, 4}. Therefore, the output is No. Input:
8 min read