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.
๐ค Master Java String Validation Problems
Checking whether a string contains only digits is a common coding round and input validation problem. Strengthen your Java string handling skills by practicing these related problems and interview-focused topics.
๐ง Java Coding Round Questions
Practice frequently asked string and validation problems.
๐งต Java String Pool & Interning
Understand how strings are stored and handled internally in Java.
๐จ Exception Handling Best Practices
Learn how to safely validate user input and handle errors.
๐ฆ Java Collections Interview Questions
Explore how strings and collections work together in real-world problems.
๐ Palindrome String Program
Another classic string problem frequently asked in interviews.
๐ Reverse String in Java
Strengthen your understanding of string traversal and manipulation.
๐ First Non-Repeated Character
Learn frequency-based string processing techniques.
๐งฎ Check Anagram Strings
Practice character counting and comparison logic.
๐ฏ Java Interview Questions (Freshers)
Common interview questions related to strings and input validation.
๐งช Advanced Java Programs (Real-World)
Apply string validation logic in real-world Java programs.