Languages
[Edit]
EN

Java - check if string contains only digits

0 points
Created by:
Dirask Admin - Marvin
1820

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

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

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

1. Using regex

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 {

    public static boolean isOnlyDigits(String stringToCheck) {
        Pattern compiledPattern = Pattern.compile("\\d+"); // or "[0-9]+"
        Matcher matcher = compiledPattern.matcher( stringToCheck );

        return matcher.matches();
    }

    public static void main(String[] args) {
        String stringWithNumbers = "123456";
        String anotherString = "1124Sample text...";

        System.out.println( isOnlyDigits( stringWithNumbers )); // true
        System.out.println( isOnlyDigits( anotherString ));     // false
    }
}

 Output: 

true
false

Note: 

The matches method only 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 isOnlyDigits(String stringToCheck) {
        for ( char charToCheck : stringToCheck.toCharArray() ) {
            if ( !Character.isDigit( charToCheck ) ) {
                return false;
            }
        }
        return true;
    }

    public static void main(String args[]) {
        String stringWithNumbers = "123456";
        String anotherString = "1124Sample text...";

        System.out.println(isOnlyDigits( stringWithNumbers )); // true
        System.out.println(isOnlyDigits( anotherString ));     // false
    }
}

Output:

true
false

Java - String (popular problems)

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