How to Check if a String Contains Only Digits in Java

Introduction

In many applications, it is often necessary to validate input to ensure that it contains only digits. This can be useful for processing user input, validating data formats, or ensuring that strings represent valid numeric values. In this blog post, we will explore various methods to check if a string contains only digits in Java.

Table of Contents

  1. Using Character.isDigit() 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.isDigit()() Method

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

Example:

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

        boolean result = containsOnlyDigits(input);

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

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

Output:

Does the string contain only digits? true

2. Using Regular Expressions

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

Example:

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

        boolean result = containsOnlyDigits(input);

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

    public static boolean containsOnlyDigits(String str) {
        return str.matches("\\d+");
    }
}

Output:

Does the string contain only digits? 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 digits.

Example:

import java.util.stream.IntStream;

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

        boolean result = containsOnlyDigits(input);

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

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

Output:

Does the string contain only digits? true

4. Using Apache Commons Lang Library

The Apache Commons Lang library provides a utility method to check if a string contains only digits. 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 CheckDigitsUsingStringUtils {
    public static void main(String[] args) {
        String input = "123456";

        boolean result = containsOnlyDigits(input);

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

    public static boolean containsOnlyDigits(String str) {
        return StringUtils.isNumeric(str);
    }
}

Output:

Does the string contain only digits? true

5. Complete Example Program

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

Example Code:

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

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

        // Using Character.isDigit() Method
        boolean resultIsDigit = containsOnlyDigitsUsingIsDigit(input);
        System.out.println("Using Character.isDigit(): " + resultIsDigit);

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

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

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

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

    public static boolean containsOnlyDigitsUsingRegex(String str) {
        return str.matches("\\d+");
    }

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

    public static boolean containsOnlyDigitsUsingStringUtils(String str) {
        return StringUtils.isNumeric(str);
    }
}

Output:

Using Character.isDigit(): 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 digits can be accomplished in multiple ways in Java. The Character.isDigit() 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