Java 8 – Check If the String Contains Only Letters or Digits

Introduction

Validating whether a string contains only letters or digits is a common requirement in various applications, particularly when dealing with user input validation, form processing, or data sanitization. While Java 8 provides a modern and efficient approach to this task using Streams, it’s also useful to understand the traditional methods used before Java 8. In this guide, we’ll explore how to check if a string contains only letters or digits 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 or digits.
  • Outputs whether the string is alphanumeric or not.

Example 1:

  • Input: "Hello123"
  • Output: "The string contains only letters or digits."

Example 2:

  • Input: "Hello@123"
  • Output: "The string does not contain only letters or digits."

Solution Steps

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

Java Program

Traditional Approach: Check If the String Contains Only Letters or Digits

/**
 * Traditional Approach: Check If the String Contains Only Letters or Digits
 * Author: https://www.rameshfadatare.com/
 */
public class CheckAlphanumericTraditional {

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

        // Step 2: Check if the string contains only letters or digits using traditional approach
        boolean isAlphanumeric = isAlphanumericTraditional(input);

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

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

Java 8 Approach: Check If the String Contains Only Letters or Digits

/**
 * Java 8: Check If the String Contains Only Letters or Digits
 * Author: https://www.rameshfadatare.com/
 */
public class CheckAlphanumericJava8 {

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

        // Step 2: Check if the string contains only letters or digits using Java 8 Streams
        boolean isAlphanumeric = isAlphanumericJava8(input);

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

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

Explanation of the Programs

  • Traditional Approach: The first program uses a for loop combined with Character.isLetterOrDigit() to check each character in the string. If any character is neither a letter nor a digit, 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::isLetterOrDigit) checks if all characters in the stream are either letters or digits.

Output Example

For both methods, the output will be:

Example 1:

Input: Hello123
Output: The string contains only letters or digits.

Example 2:

Input: Hello@123
Output: The string does not contain only letters or digits.

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-alphanumeric 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 or digits: the traditional approach using a for loop and Character.isLetterOrDigit(), 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