Count Special Characters in a String in Java
Problem
A special character is anything that isn't a letter, digit, or whitespace — punctuation and symbols like @, #, or !.
Given a string, count how many special characters it contains.
Java Program
public class CountSpecialCharacters {
public static void main(String[] args) {
String str = "Hello@World#2024!";
int count = 0;
for (char c : str.toCharArray()) {
// Anything that isn't a letter/digit or whitespace counts as special
if (!Character.isLetterOrDigit(c) && !Character.isWhitespace(c)) count++;
}
System.out.println("Special characters: " + count);
}
}Output
Core Logic
Defining a special character as 'everything that's left over' after ruling out letters, digits, and whitespace makes the check a single condition.
- 1A for-each loop visits each character of the string in turn.
- 2
Character.isLetterOrDigit(c)rules out ordinary letters and numbers. - 3
Character.isWhitespace(c)rules out spaces, tabs, and newlines. - 4Anything that fails both checks — punctuation and symbols — increments the
countvariable.
"Hello@World#2024!", the scan finds three special characters: @, #, and !.Key Point: Defining 'special' by exclusion — not a letter, not a digit, not whitespace — avoids having to list out every possible punctuation mark or symbol individually.
Why: Each character is checked once against isLetterOrDigit() and isWhitespace(), with only a running counter kept regardless of string length.
Key Concepts
Approach 2: Java 8
public class CountSpecialCharactersStream {
public static void main(String[] args) {
String str = "Hello@World#2024!";
// Keeps characters that are neither a letter/digit nor whitespace
long count = str.chars()
.filter(c -> !Character.isLetterOrDigit(c) && !Character.isWhitespace(c))
.count();
System.out.println("Special characters: " + count);
}
}
Output
Core Logic
The same 'everything left over' definition can filter a stream of character codes down to just the special characters, then count what's left.
- 1
str.chars()returns anIntStreamof the string's character codes. - 2
.filter(c -> !Character.isLetterOrDigit(c) && !Character.isWhitespace(c))keeps only characters that are neither a letter/digit nor whitespace. - 3
.count()reduces the filtered stream down to a singlelongtotal.
"Hello@World#2024!" keeps only @, #, and !, so count() returns 3.Key Point: The filter condition is the exact same boolean expression the loop version checks — the stream just changes how it's applied across the string.
Why: The stream still visits every character once, and count() reduces straight down to a single long without collecting anything.