Check if String Contains Only Digits in Java

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.