How to Check if a String Contains only Digits in Java?
Last Updated :
28 Nov, 2024
In Java, to check if a string contains only digits, we can use various methods such as simple iteration, regular expressions, streams, etc.
Example:
The example below uses the Character.isDigit() method to check each character of the string to ensure all characters are digits. This is the most simple method among all others.
Java
// Java program to check if a string
// contains only digits using Character.isDigit()
public class CheckDigits {
public static boolean onlyDigits(String s) {
// Traverse each character in the string
for (int i = 0; i < s.length(); i++) {
// Check if the character is not a digit
if (!Character.isDigit(s.charAt(i))) {
// If any character is not a digit, return false
return false;
}
}
return true; // If all characters are digits, return true
}
public static void main(String[] args) {
System.out.println(onlyDigits("1234"));
System.out.println(onlyDigits("123s"));
}
}
Other Methods to Check if a String Contains only Digits
1. Using Regular Expressions
In this method, we will use the regular expressions to check if the string matches the pattern of only digits. This method is more complex than Character.isDigit()
but still very readable and concise.
Java
// Java program to check if a string
// contains only digits using regex
import java.util.regex.*;
public class CheckDigits {
public static boolean onlyDigits(String s) {
// Regex to check if the string
// contains only digits
return s.matches("[0-9]+");
}
public static void main(String[] args) {
System.out.println(onlyDigits("1234"));
System.out.println(onlyDigits("123s"));
}
}
Explanation: In the above example, the regular expression "[0-9]+"
matches strings that contain only digits. The matches()
method returns true
if the string matches the regex.
2. Using Traversal
In this method, the idea is to traverse each character in the string and check if the character of the string contains only digits from 0 to 9. If all the character of the string contains only digits then return true, otherwise, return false.
Java
// Java program to check if a string
// contains only digits using traversal
class CheckDigits {
public static boolean onlyDigits(String s, int n)
{
// Traverse the string from
// start to end
for (int i = 0; i < n; i++) {
// Check if character is
// not a digit between 0-9
// then return false
if (s.charAt(i) < '0'
|| s.charAt(i) > '9') {
return false;
}
}
// If we reach here, that means
// all characters were digits
return true;
}
public static void main(String args[]) {
String s = "1s234";
int l = s.length();
System.out.println(onlyDigits(s, l));
}
}
Note: This approach works but is less readable than Character.isDigit()
, as it requires checking ASCII values manually.
3. Using Arraylist.contains() Method
In this method, it creates an ArrayList
of digits (0
to 9
) and checks if each character in the string is present in this list. It is less efficient and more complex than other methods.
Java
// Java program to check a string
// contains only digits using Arraylist.contains()
import java.util.*;
class CheckDigits {
public static boolean onlyDigits(String s) {
// String containing all digits
String d = "0123456789";
ArrayList<Character> n = new ArrayList<Character>();
// Add all digits to ArrayList
for (int i = 0; i < d.length(); i++) {
n.add(d.charAt(i));
}
// Traverse the string and check
// if each character is a digit
for (int i = 0; i < s.length(); i++) {
// Check if the character is not a digit
if (!n.contains(s.charAt(i))) {
return false;
}
}
// If we reach here,
// all characters are digits
return true;
}
public static void main(String args[]) {
String s = "1234";
System.out.println(onlyDigits(s));
}
}
Java program to Check whether the String contains only digits
Similar Reads
Check if a String Contains only Alphabets in Java In Java, to check if a string contains only alphabets, we have to verify each character to make sure it falls within the range of valid alphabetic characters. There are various ways to check this in Java, depending on requirements.Example: The most common and straightforward approach to validate if
4 min read
Check if a String Contains only Alphabets in Java using Regex Regular Expressions or Regex is an API for defining String patterns that can be used for searching, manipulating, and editing a text. It is widely used to define a constraint on strings such as a password. Regular Expressions are provided under java.util.regex package. For any string, here the task
2 min read
Different Ways to Remove all the Digits from String in Java Given alphanumeric string str, the task is to write a Java program to remove all the digit from this string and prints the modified string. Examples: Input: str = âGeeksForGeeks123âOutput: GeeksForGeeksExplanation: The given string contains digits 1, 2, and 3. We remove all the digit and prints the
3 min read
Java Program to Check if all digits of a number divide it Given a number n, find whether all digits of n divide it or not.Examples: Input : 128 Output : Yes 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. Input : 130 Output : No We want to test whether each digit is non-zero and divides the number. For example, with 128, we want to test d != 0 && 128
2 min read
Check if a string consists only of special characters Given string str of length N, the task is to check if the given string contains only special characters or not. If the string contains only special characters, then print âYesâ. Otherwise, print âNoâ. Examples: Input: str = â@#$&%!~âOutput: YesExplanation: Given string contains only special char
9 min read
Check if a given string is a valid number (Integer or Floating Point) in Java In the article Check if a given string is a valid number, we have discussed general approach to check whether a string is a valid number or not. In Java we can use Wrapper classes parse() methods along with try-catch blocks to check for a number. For integer number Integer class provides a static me
4 min read