isDigits()
is a NumberUtils
that is used to check if the input string contains only digits. The method returns false
if the input is null
or an empty string.
NumberUtils
The definition of NumberUtils
can be found in the Apache Commons Lang
package, which we can add to the Maven project by adding the following dependency to the pom.xml
file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the
commons-lang
package, refer to the Maven Repository.
You can import the NumberUtils
class as follows:
import org.apache.commons.lang3.math.NumberUtils;
public static boolean isDigits(final String str)
final String str
: This is the string to check.This method returns true
if the string contains only digits. Otherwise, it returns false
.
import org.apache.commons.lang3.math.NumberUtils;public class Main{public static void main(String[] args){// Example 1String stringToConvert = "23356";System.out.printf("The output of the method NumberUtils.isDigits(%s) is %s", stringToConvert, NumberUtils.isDigits(stringToConvert));System.out.println();// Example 2stringToConvert = "233sdf";System.out.printf("The output of the method NumberUtils.isDigits(%s) is %s", stringToConvert, NumberUtils.isDigits(stringToConvert));System.out.println();}}
string to convert = 23356
The method returns true
, as the input string contains only digits.
string to convert = 233sdf
The method returns false
, as the input string contains digits and alphabets.
The output of the code will be as follows:
The output of the method NumberUtils.isDigits(23356) is true
The output of the method NumberUtils.isDigits(233sdf) is false
Free Resources