Count Digits and Special Characters
Java coding interview problem for Character Problems: Count Digits and Special Characters.
Counting digits and special characters is one of the most common Java String interview questions.
Although the problem looks simple, it helps interviewers evaluate your understanding of:
- Character Classification
- String Traversal
- Character Class
- ASCII Values
- Conditional Statements
- Loops
- Time Complexity
This concept is frequently used in:
- Password Validation
- Input Validation
- Form Processing
- Text Analytics
- Data Cleaning
- Log Analysis
Mastering this problem makes many String processing interview questions easier.
Problem Statement
Given a string,
count:
- Number of digits
- Number of special characters
Ignore uppercase and lowercase letters.
Example 1
Input
Java@123
Output
Digits = 3
Special Characters = 1
Example 2
Input
Code#2026!
Output
Digits = 4
Special Characters = 2
Example 3
Input
Hello World!
Output
Digits = 0
Special Characters = 2
Special characters
(space)
!
Example 4
Input
ABC123xyz$%
Output
Digits = 3
Special Characters = 2
What are Digits and Special Characters?
Characters can be classified into multiple categories.
Alphabets
A-Z
a-z
Digits
0
1
2
3
...
9
Special Characters
Examples
@
#
$
%
&
!
*
?
_
-
+
Anything that is not a letter or digit is generally considered a special character.
Why is this Question Asked in Interviews?
Interviewers use this problem to evaluate:
- Character Classification
- Java Character API
- ASCII Knowledge
- Looping
- Conditional Logic
- Edge Case Handling
This problem also serves as the foundation for many validation algorithms.
Real-World Applications
Counting digits and special characters is widely used.
Password Validation
Example
Password@123
Validation Rules
- At least one digit
- At least one special character
Registration Forms
Ensure usernames or passwords satisfy required policies.
Data Cleaning
Remove unwanted characters from imported data.
Log File Analysis
Detect symbols and numeric values inside logs.
Financial Applications
Separate numeric values from currency symbols.
Example
$250.75
Digits
2
5
0
7
5
Special Characters
$
.
Understanding Character Classification
Suppose we have
Java@123
Read one character at a time.
Read
J
Letter
Ignore.
Read
a
Letter
Ignore.
Read
v
Letter
Ignore.
Read
a
Letter
Ignore.
Read
@
Special Character
Special = 1
Read
1
Digit
Digits = 1
Read
2
Digits = 2
Read
3
Digits = 3
Final
Digits = 3
Special = 1
ASCII Table for Digits and Special Characters
Digits occupy
48
↓
57
ASCII
Common Special Characters
| Character | ASCII |
|---|---|
| ! | 33 |
| " | 34 |
| # | 35 |
| $ | 36 |
| % | 37 |
| & | 38 |
| ' | 39 |
| ( | 40 |
| ) | 41 |
| * | 42 |
| + | 43 |
| , | 44 |
| - | 45 |
| . | 46 |
| / | 47 |
| : | 58 |
| ; | 59 |
| < | 60 |
| = | 61 |
| > | 62 |
| ? | 63 |
| @ | 64 |
Mathematical Concept
Digit Range
48
↓
57
Equivalent
'0'
↓
'9'
Special Characters
Anything
NOT
Letter
AND
NOT
Digit
ASCII Visualization
Input
A1@b#
A
↓
Letter
1
↓
Digit
@
↓
Special
b
↓
Letter
#
↓
Special
Final
Digits = 1
Special = 2
Dry Run
Input
Code@2026!
| Character | Category | Digits | Special |
|---|---|---|---|
| C | Letter | 0 | 0 |
| o | Letter | 0 | 0 |
| d | Letter | 0 | 0 |
| e | Letter | 0 | 0 |
| @ | Special | 0 | 1 |
| 2 | Digit | 1 | 1 |
| 0 | Digit | 2 | 1 |
| 2 | Digit | 3 | 1 |
| 6 | Digit | 4 | 1 |
| ! | Special | 4 | 2 |
Final
Digits = 4
Special = 2
Approach 1 — Using Character Class (Recommended)
Java provides built-in methods for character classification.
Methods
Character.isDigit()
Character.isLetter()
If a character is neither a letter nor a digit,
it is considered a special character.
Algorithm
- Initialize digit and special counters.
- Traverse every character.
- If digit, increment digit counter.
- Else if not letter, increment special counter.
- Print both counters.
Java Program
public class CountDigitsSpecialCharacters {
public static void countCharacters(String text) {
int digits = 0;
int special = 0;
for (char ch : text.toCharArray()) {
if (Character.isDigit(ch)) {
digits++;
} else if (!Character.isLetter(ch)) {
special++;
}
}
System.out.println("Digits = " + digits);
System.out.println("Special Characters = " + special);
}
public static void main(String[] args) {
countCharacters("Code@2026!");
}
}
Output
Digits = 4
Special Characters = 2
Step-by-Step Code Explanation
Initialize counters.
int digits = 0;
int special = 0;
Traverse string.
for(char ch : text.toCharArray())
Check digit.
Character.isDigit(ch)
Increment
digits++;
Otherwise
!Character.isLetter(ch)
Increment
special++;
Print results.
System.out.println(...)
Dry Run of Character Class Approach
Input
A1@b#
| Character | Action | Digits | Special |
|---|---|---|---|
| A | Ignore | 0 | 0 |
| 1 | Digit | 1 | 0 |
| @ | Special | 1 | 1 |
| b | Ignore | 1 | 1 |
| # | Special | 1 | 2 |
Final
Digits = 1
Special = 2
Advantages
- Easy to understand.
- Supports Unicode.
- Recommended interview solution.
- Highly readable.
Drawbacks
- Slight method-call overhead.
- Uses built-in APIs.
Approach 2 — Using ASCII Range Checks
Instead of using the Character class,
we can use ASCII values.
Digits occupy
'0'
↓
'9'
Everything that is not a letter or digit is a special character.
Algorithm
- Traverse string.
- Check digit using ASCII range.
- Ignore letters.
- Count remaining characters as special.
Java Program
public class CountDigitsSpecialASCII {
public static void countCharacters(String text) {
int digits = 0;
int special = 0;
for (char ch : text.toCharArray()) {
if (ch >= '0' && ch <= '9') {
digits++;
} else if (!((ch >= 'A' && ch <= 'Z')
|| (ch >= 'a' && ch <= 'z'))) {
special++;
}
}
System.out.println("Digits = " + digits);
System.out.println("Special Characters = " + special);
}
public static void main(String[] args) {
countCharacters("Code@2026!");
}
}
Output
Digits = 4
Special Characters = 2
Step-by-Step Code Explanation
Check digit.
ch >= '0' && ch <= '9'
Increment
digits++;
Check alphabet.
'A'-'Z'
or
'a'-'z'
Ignore.
Otherwise
Increment
special++;
Time & Space Complexity
| Approach | Time | Extra Space |
|---|---|---|
| Character Class | O(n) | O(1) |
| ASCII Range Check | O(n) | O(1) |
Where
- n = Length of the string
Comparison of Approaches
| Feature | Character Class | ASCII Range |
|---|---|---|
| Interview Friendly | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| Performance | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| Unicode Support | ✅ | ❌ |
| Easy to Read | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
Advantages
- Both approaches execute in O(n) time.
- Character Class supports Unicode and is production-ready.
- ASCII Range Check is slightly faster for English text.
- Both efficiently count digits and special characters.
Drawbacks
- Character Class has minor method-call overhead.
- ASCII Range Check works only for English ASCII characters.
- Neither approach demonstrates functional programming techniques.
Approach 3 — Using Enhanced For Loop
The Enhanced For Loop (for-each) provides one of the cleanest and most readable ways to iterate through characters in a string.
It avoids manual index handling while keeping the solution simple.
Why Enhanced For Loop?
Instead of writing
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
}
We can simply write
for (char ch : text.toCharArray()) {
}
This makes the code shorter and easier to understand.
Algorithm
- Initialize digit and special counters.
- Convert string into a character array.
- Traverse every character.
- Count digits.
- Count special characters.
- Print the result.
Java Program
public class CountDigitsSpecialEnhanced {
public static void countCharacters(String text) {
int digits = 0;
int special = 0;
for (char ch : text.toCharArray()) {
if (Character.isDigit(ch)) {
digits++;
} else if (!Character.isLetter(ch)) {
special++;
}
}
System.out.println("Digits = " + digits);
System.out.println("Special Characters = " + special);
}
public static void main(String[] args) {
countCharacters("Java@123#");
}
}
Output
Digits = 3
Special Characters = 2
Advantages
- Very readable.
- Less code.
- No index management.
- Excellent interview solution.
Drawbacks
- Cannot directly access character indexes.
- Uses Character class methods.
Approach 4 — Using Java Streams
Java 8 Streams provide a concise functional programming solution.
Instead of manually traversing the string,
Streams filter digits and special characters separately.
Algorithm
- Convert string into an IntStream.
- Filter digits.
- Count digits.
- Filter special characters.
- Count special characters.
Java Program
public class CountDigitsSpecialStreams {
public static void countCharacters(String text) {
long digits = text.chars()
.filter(Character::isDigit)
.count();
long special = text.chars()
.filter(ch ->
!Character.isLetterOrDigit(ch))
.count();
System.out.println("Digits = " + digits);
System.out.println("Special Characters = " + special);
}
public static void main(String[] args) {
countCharacters("Code@2026!");
}
}
Output
Digits = 4
Special Characters = 2
Advantages
- Modern Java.
- Functional programming.
- Very concise.
- Easy to combine with Stream operations.
Drawbacks
- Stream overhead.
- Harder for beginners.
- Less common during coding interviews.
Approach 5 — Using Regular Expressions (Regex)
Regular Expressions provide another elegant solution.
We remove everything except digits,
and similarly remove everything except special characters.
Algorithm
- Remove everything except digits.
- Count remaining characters.
- Remove everything except special characters.
- Count remaining characters.
Java Program
public class CountDigitsSpecialRegex {
public static void countCharacters(String text) {
int digits =
text.replaceAll("[^0-9]", "")
.length();
int special =
text.replaceAll("[A-Za-z0-9]", "")
.length();
System.out.println("Digits = " + digits);
System.out.println("Special Characters = " + special);
}
public static void main(String[] args) {
countCharacters("Code@2026!");
}
}
Output
Digits = 4
Special Characters = 2
Advantages
- Very compact.
- Easy to understand.
- Useful for text processing.
Drawbacks
- Regex is slower than iteration.
- Creates additional String objects.
- Not suitable for high-performance applications.
Unicode Considerations
Java uses UTF-16 encoding for String.
Examples
こんにちは
नमस्ते
😊
The Character class correctly recognizes Unicode digits.
Examples
١٢٣
(Arabic digits)
ASCII range checks ('0' to '9') only work for English digits.
Similarly,
the Regex examples shown above are based on ASCII character ranges.
Edge Cases
| Input | Digits | Special Characters |
|---|---|---|
"" |
0 | 0 |
"12345" |
5 | 0 |
"@#$%" |
0 | 4 |
"Java" |
0 | 0 |
"A1@b#" |
1 | 2 |
" " |
0 | 1 |
null |
Handle appropriately |
Time & Space Complexity
| Approach | Time | Extra Space |
|---|---|---|
| Character Class | O(n) | O(1) |
| ASCII Range Check | O(n) | O(1) |
| Enhanced For Loop | O(n) | O(1) |
| Java Streams | O(n) | O(1) |
| Regex | O(n) | O(n) |
Where
- n = Length of the string
Note: Regex creates intermediate strings, increasing memory usage.
Comparison of All Approaches
| Approach | Interview Friendly | Performance | Unicode Support | Best Use Case |
|---|---|---|---|---|
| Character Class | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ✅ | Recommended interview solution |
| ASCII Range Check | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ❌ | ASCII-only strings |
| Enhanced For Loop | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ✅ | Production code |
| Java Streams | ⭐⭐⭐⭐ | ⭐⭐⭐ | ✅ | Modern Java |
| Regex | ⭐⭐⭐ | ⭐⭐ | Limited* | Quick text processing |
*The regex shown uses ASCII ranges. Unicode-aware patterns require different expressions.
Common Interview Mistakes
Mistake 1
Counting letters as special characters.
Wrong
Java123
Only
1
2
3
are digits.
Letters should not be counted as special characters.
Mistake 2
Ignoring spaces.
Example
Hello World
The space
' '
is a special character in this problem unless the interviewer specifies otherwise.
Mistake 3
Using ASCII checks for Unicode digits.
Example
١٢٣
Arabic digits are recognized by Character.isDigit() but not by ASCII range checks.
Mistake 4
Using Regex in performance-critical code.
Regex creates additional objects and is slower than direct iteration.
Mistake 5
Ignoring null or empty strings.
Always validate the input before processing.
if (text == null || text.isEmpty()) {
return;
}
Interview Follow-up Questions
Q1. Why is Character.isDigit() preferred?
Q2. Why is ASCII checking faster?
Q3. Why is Regex slower?
Q4. How do you support Unicode digits?
Q5. Should spaces be counted as special characters?
Q6. Can this be solved using Streams?
Q7. How would you count letters, digits, and symbols in one traversal?
Q8. What is the overall space complexity?
Q9. Which solution is best for production?
Q10. How would you process a file with millions of characters?
Related Problems
- Count Uppercase and Lowercase Characters
- Toggle Case
- Remove Special Characters
- Character Frequency
- Count Vowels and Consonants
- Password Validation
- Reverse a String
- Most Frequent Character
- First Non-Repeating Character
Key Takeaways
- Counting digits and special characters is a common String interview problem.
- Character Class is the safest and most recommended approach because it supports Unicode.
- ASCII Range Check is slightly faster but works only for ASCII characters.
- Enhanced For Loop provides clean and maintainable production-quality code.
- Java Streams offer a concise functional programming solution.
- Regex is useful for quick text processing but is slower and allocates additional memory.
Frequently Asked Interview Questions
Q1. Which solution is best for interviews?
The Character Class approach is the recommended solution because it is readable, Unicode-aware, and widely accepted.
Q2. Which solution is fastest?
For ASCII input, ASCII Range Check is generally the fastest due to simple character comparisons.
Q3. Why use Character.isDigit()?
It correctly recognizes digits across multiple Unicode scripts, making it suitable for international applications.
Q4. Why is Regex slower?
Regex performs pattern matching and creates intermediate strings, increasing CPU and memory usage.
Q5. Can digits and special characters be counted in one traversal?
Yes.
Character Class, ASCII Range Check, and Enhanced For Loop count both values during a single pass, resulting in O(n) time complexity.
Interview Tip
If an interviewer asks:
"Count the digits and special characters in a string."
Start with the Character Class solution because it is the standard Java approach.
Before coding, clarify:
- Should spaces be counted as special characters?
- Should Unicode digits be supported?
- How should letters be handled?
- How should
nullor empty strings be handled?
Then discuss progressively advanced approaches:
- Character Class (recommended)
- ASCII Range Check (ASCII optimization)
- Enhanced For Loop (clean production code)
- Java Streams (functional programming)
- Regex (quick text-processing solution)
This demonstrates strong Java fundamentals, knowledge of the Java Character API, and an understanding of the trade-offs between different implementations.