Languages
[Edit]
EN

Java - check if string only contains numbers

0 points
Created by:
Lia-Perez
355

In this article, we would like to show you how to check if the string only contains numbers in Java.

1. Using regex

In this example, we use a regular expression (regex) with Pattern.matcher() to check if the strings contain only numbers.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Example {

    public static void main(String[] args) {
        String numbers = "1234";
        String text = "ABC";

        String regex = "^[0-9]+$";  // regex to check if string contains only digits
        Pattern pattern = Pattern.compile(regex);  // compiles the regex

        // find match between given string and pattern
        Matcher matcherNumbers = pattern.matcher(numbers);
        Matcher matcherText = pattern.matcher(text);

        // return true if the string matched the regex
        Boolean numbersMatches = matcherNumbers.matches();
        Boolean textMatches = matcherText.matches();

        System.out.println(numbersMatches); // true
        System.out.println(textMatches);    // false
    }
}

Output:

true
false

2. Using Character.isDigit()

In this example, we create a function that loops through the string and checks if each character is a digit with Character.isDigit(char ch) method.

Practical example:

public class Example {

    public static void main(String[] args) {
        String numbers = "1234";
        String text = "ABC";

        System.out.println(onlyNumbers(numbers));     // true
        System.out.println(onlyNumbers(text));        // false
    }

    public static boolean onlyNumbers(String string) {
        if (string == null || string.isEmpty()) {
            return false;
        }
        for (int i = 0; i < string.length(); ++i) {
            if (!Character.isDigit(string.charAt(i))) {
                return false;
            }
        }
        return true;
    }
}

Output:

true
false

Java - String (popular problems)

Java - check if string only contains numbers
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join