Java 8 – How to Check if a String is Numeric

Introduction

In Java, determining whether a string contains only numeric characters is a common requirement, especially when processing user input or data validation. Java 8 introduced several features that make this task more straightforward and efficient, including the Stream API and lambda expressions.

In this guide, we’ll explore various ways to check if a string is numeric using Java 8 features. We’ll cover approaches using regular expressions, the Stream API, and other utility methods.

Table of Contents

  • Problem Statement
  • Solution Steps
  • Java Program
    • Example 1: Using Character.isDigit()
    • Example 2: Using Regular Expressions
    • Example 3: Using Apache Commons Lang’s NumberUtils
    • Example 4: Using Stream API
  • Conclusion

Problem Statement

You need to verify whether a given string contains only numeric characters. This check is essential in various scenarios, such as validating user input, parsing strings to numbers, and ensuring data integrity.

Example:

  • Problem: Determine if the string "12345" is numeric, but "12a45" is not.
  • Goal: Implement methods in Java 8 to efficiently check if a string consists only of numeric characters.

Solution Steps

  1. Use Character.isDigit(): Check each character in the string to determine if it is a digit.
  2. Use Regular Expressions: Leverage regular expressions to match numeric patterns.
  3. Use Apache Commons Lang: Utilize NumberUtils.isDigits() for a robust solution.
  4. Use the Stream API: Apply the Stream API to perform the check in a functional style.

Java Program

Example 1: Using Character.isDigit()

The Character.isDigit() method can be used to iterate through each character in the string and check if it’s a digit.

/**
 * Java 8 - Check if a String is Numeric using Character.isDigit()
 * Author: https://www.rameshfadatare.com/
 */
public class NumericCheckExample1 {

    public static void main(String[] args) {
        String str = "12345";
        boolean isNumeric = isNumeric(str);
        System.out.println("Is the string numeric? " + isNumeric);
    }

    public static boolean isNumeric(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        for (char c : str.toCharArray()) {
            if (!Character.isDigit(c)) {
                return false;
            }
        }
        return true;
    }
}

Output

Is the string numeric? true

Explanation

  • Character.isDigit(c): Checks if each character in the string is a digit. If any character is not a digit, the method returns false.

Example 2: Using Regular Expressions

Regular expressions provide a concise way to check if a string matches a numeric pattern.

import java.util.regex.Pattern;

/**
 * Java 8 - Check if a String is Numeric using Regular Expressions
 * Author: https://www.rameshfadatare.com/
 */
public class NumericCheckExample2 {

    private static final Pattern NUMERIC_PATTERN = Pattern.compile("\\d+");

    public static void main(String[] args) {
        String str = "12345";
        boolean isNumeric = isNumeric(str);
        System.out.println("Is the string numeric? " + isNumeric);
    }

    public static boolean isNumeric(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        return NUMERIC_PATTERN.matcher(str).matches();
    }
}

Output

Is the string numeric? true

Explanation

  • \\d+: The regular expression \\d+ matches one or more digits. The matches() method checks if the entire string consists of digits.

Example 3: Using Apache Commons Lang’s NumberUtils

If you have access to Apache Commons Lang, the NumberUtils.isDigits() method provides a robust and convenient way to check if a string is numeric.

import org.apache.commons.lang3.math.NumberUtils;

/**
 * Java 8 - Check if a String is Numeric using Apache Commons Lang
 * Author: https://www.rameshfadatare.com/
 */
public class NumericCheckExample3 {

    public static void main(String[] args) {
        String str = "12345";
        boolean isNumeric = NumberUtils.isDigits(str);
        System.out.println("Is the string numeric? " + isNumeric);
    }
}

Output

Is the string numeric? true

Explanation

  • NumberUtils.isDigits(str): This method checks if the string contains only digits. It’s a reliable utility method provided by Apache Commons Lang.

Example 4: Using Stream API

Java 8’s Stream API can also be used to check if a string is numeric in a more functional style.

import java.util.stream.IntStream;

/**
 * Java 8 - Check if a String is Numeric using Stream API
 * Author: https://www.rameshfadatare.com/
 */
public class NumericCheckExample4 {

    public static void main(String[] args) {
        String str = "12345";
        boolean isNumeric = isNumeric(str);
        System.out.println("Is the string numeric? " + isNumeric);
    }

    public static boolean isNumeric(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        return str.chars().allMatch(Character::isDigit);
    }
}

Output

Is the string numeric? true

Explanation

  • str.chars().allMatch(Character::isDigit): Converts the string to an IntStream of characters and checks if all characters are digits using allMatch().

Conclusion

In Java 8, there are several ways to check if a string is numeric, ranging from traditional loops and regular expressions to using the Stream API for a more functional approach. Depending on your use case, any of these methods can be employed effectively. For simpler checks, Character.isDigit() and regular expressions work well, while Apache Commons Lang offers a robust utility method for this task. The Stream API provides a concise and functional alternative, aligning with modern Java practices.

Leave a Comment

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

Scroll to Top