In this tutorial, we’ll explore different ways to check whether a given string contains only numeric digits in Java. This is a common validation step in many applications and interview coding problems.
๐งช Problem Statement
Given a string, determine if it contains only digits from 0-9.
๐ Example
- Input:
"123456"
→ Output: true - Input:
"abc123"
→ Output: false - Input:
""
→ Output: false
✅ Approach 1: Using Character Check
public class DigitCheck {
public static void main(String[] args) {
String input = "123456";
System.out.println("Contains only digits: " + containsOnlyDigits(input));
}
static boolean containsOnlyDigits(String str) {
if(str == null || str.isEmpty()) return false;
for(char c : str.toCharArray()) {
if(!Character.isDigit(c)) return false;
}
return true;
}
}
✅ Approach 2: Using Regular Expression
public class DigitCheckRegex {
public static void main(String[] args) {
String input = "123abc";
System.out.println("Contains only digits: " + input.matches("\\d+"));
}
}
✅ Output
Contains only digits: true
๐ง Interview Tip
Using Character.isDigit()
is a safe way to handle each character. Regex is faster to implement but might not give the best performance in tight loops or large datasets.
๐ Conclusion
We have discussed multiple ways to check if a string contains only digits in Java. Choose the method based on your requirement — character-by-character for better control, or regex for simplicity.
This problem is common in coding tests like those listed in Java Coding Round Questions.