VOOZH about

URL: https://www.geeksforgeeks.org/java/check-if-a-string-contains-only-alphabets-in-java-using-ascii-values/

⇱ Check if a String Contains Only Alphabets in Java using ASCII Values - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if a String Contains Only Alphabets in Java using ASCII Values

Last Updated : 11 Jul, 2025

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 characters in a string within this domain pool then the string is surely only alphabetic.

Examples:

Input: GeeksforGeeks
Output: True

Input: Geeks4Geeks
Output: False

Input: null
Output: False

In this article, the characters of the string are checked one by one using their ASCII values.

Algorithm:

  1. Get the string
  2. Match the string: 
    • Check if the string is empty or not. If empty, return false
    • Check if the string is null or not. If null, return false.
    • If the string is neither empty nor null, then check the string characters one by one for alphabet using ASCII values.
  3. Return true if matched

Example 1:


Output
true

Complexity Analysis:

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

Example 2:


Output
Test Case 1:
Input: GeeksforGeeks
Output: true

Test Case 2:
Input: Geeks4Geeks
Output: false

Test Case 3:
Input: null
Output: false

Test Case 4:
Input: 
Output: false

Complexity Analysis:

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

Related Articles:

Comment