In data handling, there can be scenarios where it is required to allocate appropriate values to the corresponding data types. More specifically, this requirement comes into effect when the integer values are allocated as strings and vice versa. In such cases, analyzing if a string comprises only digits filters out the unwanted values and ensures proper allocation of values by placing only the relevant values.
This blog will demonstrate the approaches to verify if a string comprises only digits or not in Java.
How to Check if a String Contains Only Digits in Java?
The following approaches can be utilized to verify if a string comprises only digits:
- “Character.isDigit()” Method.
- “charAt()” Method.
- “contains()” Method.
- “Regular Expression”.
Approach 1: Check if a String Contains Only Digits in Java Using the “Character.isDigit()” Method
The “Character.isDigit()” method identifies whether the target character is a digit or not, which is the requirement. The “charAt()” method, however, gives the character at the particular index in a string.
Syntax
public static boolean isDigit(char)
In this syntax, “char” corresponds to the character that needs to be checked for the character.
Note: This method gives a Boolean value based on the character being digit or not.
public char charAt(in)
In the given syntax, “in” points to the character’s index to be retrieved.
Example
Now, let’s overview the below-stated example explaining the discussed concept:
public class Digitscontain {
public static boolean containDigits(String givenString, int len){
for (int i = 0; i < len; i++) {
if (!Character.isDigit(givenString.charAt(i))) {
return false;
}}
return true;
}
public static void main(String args[]){
String string = "123";
int stringLength = string.length();
System.out.println(containDigits(string, stringLength));
String string2 = "abc123";
int stringLength2 = string2.length();
System.out.println(containDigits(string2, stringLength2));
}}
In these code lines:
- Define a function named “containDigits()” having the stated parameters. These parameters represent the passed string and its length, respectively.
- In the function body, iterate through the string by applying the “for” loop and the “Character.isDigit()” method combined with the “not (!)” operator and the “charAt()” method.
- This is done to return the corresponding Boolean value based on the contained or not contained digits in the string.
- In “main”, initialize the string that needs to be evaluated and return its length via the “length()” method.
- Now, invoke the defined function and pass the string and its computed length as its arguments.
- Lastly, define another string and repeat the same procedure with it as well.
Output
This outcome verifies that the former string contains only the digits while it is not the scenario with the latter one.
Approach 2: Check if a String Contains Only Digits in Java Using the “charAt()” Method
The “charAt()” method can be used here to apply a check upon the string characters for digits with the help of the “OR(||)” operator:
public class Digitscontain {
public static boolean containDigits(String givenString, int len){
for (int i = 0; i < len; i++) {
if (givenString.charAt(i) < '0' || givenString.charAt(i) > '9') {
return false;
}}
return true;
}
public static void main(String args[]){
String string = "123";
int stringLength = string.length();
System.out.println(containDigits(string, stringLength));
String string2 = "abc123";
int stringLength2 = string2.length();
System.out.println(containDigits(string2, stringLength2));
}}
In this code snippet:
- Likewise, define the stated function comprising the passed string and its length.
- In the function definition, check if the string comprises the digits from “0” to “9” in it using the “OR(||)” operator and return a Boolean outcome based on that accordingly.
- In “main”, initialize the string that needs to be evaluated and return its length via the “length()” method.
- Now, likewise, invoke the defined function and pass the string and its computed length as its arguments.
- Lastly, define another string and repeat the same procedure with it as well.
Output
The output implies that the Boolean values are returned accordingly.
Include the below-stated package in the next example to access all the features in the “java.util” package:
import java.util.*;
Approach 3: Check/Verify if a String Contains Only Digits in Java Using the “contains()” Method
The “contains()” method verifies if a string contains a sequence of characters. It gives “true” if the characters are contained and “false” otherwise. This method checks for the digits (defined as a string) in the corresponding string.
Syntax
public boolean contains(char)
In this syntax, “char” represents the characters that need to be searched.
Example
Now, go through the below-stated demonstration:
public class Digitscontain {
public static boolean containDigits(String givenString, int len){
String integers = "0123456789";
ArrayList<Character> givenList = new ArrayList<Character>();
for(int i= 0;i<integers.length();i++){
givenList.add(integers.charAt(i));
}
for (int i = 0; i < len; i++) {
if (!givenList.contains(givenString.charAt(i))) {
return false;
}}
return true;
}
public static void main(String args[]){
String string = "123";
int stringLength = string.length();
System.out.println(containDigits(string, stringLength));
String string2 = "abc123";
int stringLength2 = string2.length();
System.out.println(containDigits(string2, stringLength2));
}}
In this code block:
- In the discussed defined function, initialize the string comprising all the possible digits.
- In the next step, create an ArrayList of character type.
- After that, iterate through the integers contained in a string via the “for” loop and append them to the ArrayList.
- Now, specify another “for” loop that iterates the passed string and matches the iterated characters with those in the ArrayList via the “contains()” method.
- It is such that the corresponding Boolean outcome is retrieved based on the matched or unmatched string characters with the ArrayList integers (digits).
Output
Import the following package to work with regular expressions:
import java.util.regex.*;
Approach 4: Check if a String Contains Only Digits in Java Using “Regular Expression”
The “compile()” method of the “Pattern” class in Java is utilized to create a pattern via the regular expression that is passed as an argument to the method. It is such that it matches a text based on the regular expression pattern. This approach can be applied to match the string based on the particular Regular Expression.
Syntax
Pattern compile(regex)
Here, “regex” corresponds to the provided regular expression compiled to a pattern.
Example
Now, consider the below-stated code explaining the discussed concept:
public class Digitscontain {
public static boolean containDigits(String givenString, int len){
String numRegex = "[0-9]+";
Pattern x = Pattern.compile(numRegex);
if (givenString == null) {
return false;
}
Matcher val = x.matcher(givenString);
return val.matches();
}
public static void main(String args[]){
String string = "123";
int stringLength = string.length();
System.out.println(containDigits(string, stringLength));
String string2 = "abc123";
int stringLength2 = string2.length();
System.out.println(containDigits(string2, stringLength2));
}}
According to this code:
- In the function definition, specify the regular expression i.e., digits that need to be matched.
- Now, apply the “compile()” method of the Pattern class to create a pattern via the defined regular expression.
- Also, check for the “null” condition upon the string.
- After that, use the “Matcher” class’s “matches()” method to match the passed string against the pattern and retrieve the corresponding Boolean outcome.
- In “main”, repeat the discussed steps for initializing the strings, computing their lengths, and passing them to the function to be evaluated accordingly.
Output
These values imply that the former string comprises the digits while it is not the case with the latter one.
Conclusion
To check if a string comprises only digits, apply the “Character.isDigit()” method, the “charAt()” method, the “contains()” method, or the “Regular Expression” approach. These approaches apply this operation via a user-defined function.