Java - check if string contains only digits

12 points
Created by:

In this article, we would like to show you how in Javacheck if a string contains only digits.

Quick solution:

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

Pattern pattern = Pattern.compile("\\d+");    // or "[0-9]+"
Matcher matcher = pattern.matcher("123456");

System.out.println(matcher.matches());        // true  <---- because "123456" contains only numbers


Below we present 2 methods that check if a string contains only numbers:

  1. Using regular expressions
  2. Using the Character.isDigit() method

1. Using regular expressions

In Java, the Matcher class and the Pattern class are most often used to operate on regular expressions. The isOnlyDigits method returns true if the string contains only numbers otherwise it returns false.

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

public class StringExample {

    private static final Pattern DIGITS_PATTERN = Pattern.compile("\\d+"); // or "[0-9]+"

    public static boolean containsOnlyDigits(String text) {
        Matcher matcher = DIGITS_PATTERN.matcher(text);
        return matcher.matches();

    public static void main(String[] args) {

        System.out.println(containsOnlyDigits("123456"));               // true
        System.out.println(containsOnlyDigits("1234Sample text..." ));  // false




The matches method matches the entire string (not fragments), so there is no need to use ^ and $ in the regular expression.

2. Using Character.isDigit() method

In the solution below, we will convert a string to an array of characters, then go through it and check if each character is a number.

public class StringExample {

    public static boolean containsOnlyDigits(String text) {
        for (char entry : text.toCharArray()) {
            if (!Character.isDigit(entry)) {
                return false;
        return true;

    public static void main(String args[]) {

        System.out.println(containsOnlyDigits("123456"));              // true
        System.out.println(containsOnlyDigits("1234Sample text..."));  // false


Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - check if string contains only digits

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.

❤️💻 🙂