Java 8 – Check if the String Contains Only Letters

Introduction

Validating whether a string contains only letters is a common requirement in many applications, particularly when handling user input, form validation, or text processing. While Java 8 provides a modern and efficient approach to this task using Streams, it’s also beneficial to understand the traditional methods used before Java 8. In this guide, we will explore how to check if a string contains only letters using both the traditional approach and Java 8 Streams.

Problem Statement

The task is to create a Java program that:

  • Accepts a string as input.
  • Checks if the string contains only letters.
  • Outputs whether the string is alphabetic or not.

Example 1:

  • Input: "HelloWorld"
  • Output: "The string contains only letters."

Example 2:

  • Input: "Hello123"
  • Output: "The string does not contain only letters."

Solution Steps

  1. Input String: Start with a string that can either be hardcoded or provided by the user.
  2. Check for Letters (Traditional Approach): Use the charAt() method and Character.isLetter() to validate each character.
  3. Check for Letters (Java 8 Streams): Use the Stream API to check if all characters in the string are letters.
  4. Display the Result: Print whether the string contains only letters or not.

Java Program

Traditional Approach: Check if the String Contains Only Letters

/**
 * Traditional Approach: Check if the String Contains Only Letters
 * Author: https://www.rameshfadatare.com/
 */
public class CheckLettersTraditional {

    public static void main(String[] args) {
        // Step 1: Take input string
        String input = "HelloWorld";

        // Step 2: Check if the string contains only letters using traditional approach
        boolean isAlphabetic = isAlphabeticTraditional(input);

        // Step 3: Display the result
        if (isAlphabetic) {
            System.out.println("The string contains only letters.");
        } else {
            System.out.println("The string does not contain only letters.");
        }
    }

    // Method to check if a string contains only letters (traditional approach)
    public static boolean isAlphabeticTraditional(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (!Character.isLetter(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }
}

Java 8 Approach: Check if the String Contains Only Letters

/**
 * Java 8: Check if the String Contains Only Letters
 * Author: https://www.rameshfadatare.com/
 */
public class CheckLettersJava8 {

    public static void main(String[] args) {
        // Step 1: Take input string
        String input = "HelloWorld";

        // Step 2: Check if the string contains only letters using Java 8 Streams
        boolean isAlphabetic = isAlphabeticJava8(input);

        // Step 3: Display the result
        if (isAlphabetic) {
            System.out.println("The string contains only letters.");
        } else {
            System.out.println("The string does not contain only letters.");
        }
    }

    // Method to check if a string contains only letters (Java 8 Streams approach)
    public static boolean isAlphabeticJava8(String str) {
        return str.chars().allMatch(Character::isLetter);
    }
}

Explanation of the Programs

  • Traditional Approach: The first program uses a for loop combined with Character.isLetter() to check each character in the string. If any character is not a letter, the method returns false; otherwise, it returns true.

  • Java 8 Approach: The second program uses the Stream API. The chars() method converts the string into an IntStream, and allMatch(Character::isLetter) checks if all characters in the stream are letters.

Output Example

For both methods, the output will be:

Example 1:

Input: HelloWorld
Output: The string contains only letters.

Example 2:

Input: Hello123
Output: The string does not contain only letters.

Advanced Considerations

  1. Case Sensitivity: Both methods consider all alphabetic characters, regardless of case. Uppercase and lowercase letters are treated equally as valid letters.

  2. Performance Considerations: Both methods are efficient for typical string lengths. The traditional method is straightforward and easy to understand, while the Java 8 approach is more concise and leverages modern Java features.

  3. Handling Edge Cases: Both methods handle empty strings by returning true, as there are no non-letter characters present. You might want to adjust this behavior based on specific application requirements.

Conclusion

This guide provides two methods for checking if a string contains only letters: the traditional approach using a for loop and Character.isLetter(), and a more modern approach using Java 8 Streams. Both methods are effective, but the Java 8 approach offers a more functional and concise solution. Depending on your needs and the style of your codebase, either method can be used to achieve the desired result.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top