How to Check if a String Contains Only Letters in Java

Introduction

Validating whether a string contains only letters is a common task in text processing. This can be useful for ensuring that user inputs, data fields, and other text elements meet specific criteria. In this blog post, we will explore various methods to check if a string contains only letters in Java.

Table of Contents

  1. Using Character.isLetter() Method
  2. Using Regular Expressions
  3. Using Java 8 Stream API
  4. Using Apache Commons Lang Library
  5. Complete Example Program
  6. Conclusion

1. Using Character.isLetter()() Method

The Character.isLetter() method can be used to check each character in the string to determine if it is a letter.

Example:

public class CheckLettersUsingIsLetter {
    public static void main(String[] args) {
        String input = "HelloWorld";

        boolean result = containsOnlyLetters(input);

        System.out.println("Does the string contain only letters? " + result);
    }

    public static boolean containsOnlyLetters(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (!Character.isLetter(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }
}

Output:

Does the string contain only letters? true

2. Using Regular Expressions

Regular expressions provide a concise way to check if a string contains only letters.

Example:

public class CheckLettersUsingRegex {
    public static void main(String[] args) {
        String input = "HelloWorld";

        boolean result = containsOnlyLetters(input);

        System.out.println("Does the string contain only letters? " + result);
    }

    public static boolean containsOnlyLetters(String str) {
        return str.matches("[a-zA-Z]+");
    }
}

Output:

Does the string contain only letters? true

3. Using Java 8 Stream API

Java 8 introduced the Stream API, which provides a modern and functional approach to check if a string contains only letters.

Example:

import java.util.stream.IntStream;

public class CheckLettersUsingStream {
    public static void main(String[] args) {
        String input = "HelloWorld";

        boolean result = containsOnlyLetters(input);

        System.out.println("Does the string contain only letters? " + result);
    }

    public static boolean containsOnlyLetters(String str) {
        return str.chars().allMatch(Character::isLetter);
    }
}

Output:

Does the string contain only letters? true

4. Using Apache Commons Lang Library

The Apache Commons Lang library provides a utility method for checking whether a string contains only letters. This method simplifies the validation process.

Maven Dependency:

Add the following dependency to your pom.xml file:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

Example:

import org.apache.commons.lang3.StringUtils;

public class CheckLettersUsingStringUtils {
    public static void main(String[] args) {
        String input = "HelloWorld";

        boolean result = containsOnlyLetters(input);

        System.out.println("Does the string contain only letters? " + result);
    }

    public static boolean containsOnlyLetters(String str) {
        return StringUtils.isAlpha(str);
    }
}

Output:

Does the string contain only letters? true

5. Complete Example Program

Here is a complete program that demonstrates all the methods discussed above to check if a string contains only letters.

Example Code:

import java.util.stream.IntStream;
import org.apache.commons.lang3.StringUtils;

public class CheckLettersExample {
    public static void main(String[] args) {
        String input = "HelloWorld";

        // Using Character.isLetter() Method
        boolean resultIsLetter = containsOnlyLettersUsingIsLetter(input);
        System.out.println("Using Character.isLetter(): " + resultIsLetter);

        // Using Regular Expressions
        boolean resultRegex = containsOnlyLettersUsingRegex(input);
        System.out.println("Using Regular Expressions: " + resultRegex);

        // Using Java 8 Stream API
        boolean resultStream = containsOnlyLettersUsingStream(input);
        System.out.println("Using Java 8 Stream API: " + resultStream);

        // Using Apache Commons Lang StringUtils
        boolean resultStringUtils = containsOnlyLettersUsingStringUtils(input);
        System.out.println("Using Apache Commons Lang StringUtils: " + resultStringUtils);
    }

    public static boolean containsOnlyLettersUsingIsLetter(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (!Character.isLetter(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

    public static boolean containsOnlyLettersUsingRegex(String str) {
        return str.matches("[a-zA-Z]+");
    }

    public static boolean containsOnlyLettersUsingStream(String str) {
        return str.chars().allMatch(Character::isLetter);
    }

    public static boolean containsOnlyLettersUsingStringUtils(String str) {
        return StringUtils.isAlpha(str);
    }
}

Output:

Using Character.isLetter(): true
Using Regular Expressions: true
Using Java 8 Stream API: true
Using Apache Commons Lang StringUtils: true

6. Conclusion

Checking if a string contains only letters can be accomplished in multiple ways in Java. The Character.isLetter() method is straightforward and easy to understand, while regular expressions provide a concise solution. The Java 8 Stream API offers a modern and functional approach, and the Apache Commons Lang library simplifies the task with a utility method.

By understanding these different methods, you can choose the one that best fits your needs and coding style. Happy coding!

Comments