Introduction
Counting the number of words in a sentence is one of the most common string-processing tasks in Java. It is widely used in:
- Text editors
- Word counters
- Search engines
- Chat applications
- Natural Language Processing (NLP)
- Resume analyzers
- Input validation
- Content management systems
Although counting words appears simple, real-world text often contains:
- Multiple spaces
- Tabs
- Newline characters
- Punctuation
- Empty strings
A good solution should correctly handle all these cases.
For example:
Input:
Java is a powerful programming language
Output:
6 words
This guide covers five practical methods to count words in Java, along with performance comparisons, edge cases, and best practices.
What is a Word?
In most Java programs, a word is considered any sequence of characters separated by whitespace.
Whitespace includes:
- Space (
) - Tab (
\t) - New line (
\n) - Carriage return (
\r)
Example:
Hello Java
Words:
Hello
Java
Count = 2
Method 1: Using split() (Recommended)
The easiest and most widely used approach is split().
public class CountWordsSplit {
public static int countWords(String sentence) {
if (sentence == null ||
sentence.trim().isEmpty()) {
return 0;
}
String[] words = sentence.trim().split("\\s+");
return words.length;
}
public static void main(String[] args) {
System.out.println(
countWords("Hello World Java"));
System.out.println(
countWords(" Multiple spaces "));
System.out.println(
countWords(""));
System.out.println(
countWords(null));
}
}
Output
3
2
0
0
How It Works
Suppose the input is
Java Programming Language
Step 1
trim()
Removes leading and trailing spaces.
Step 2
split("\\s+")
Splits using one or more whitespace characters.
Result
["Java",
"Programming",
"Language"]
Length = 3
Advantages
- Simple
- Easy to understand
- Handles multiple spaces
- Most commonly used
Disadvantages
- Creates an array of strings
- Slight memory overhead
Time Complexity
O(n)
Space Complexity
O(n)
Method 2: Using StringTokenizer
StringTokenizer is an older Java utility for splitting strings.
import java.util.StringTokenizer;
public class CountWordsTokenizer {
public static int countWords(String sentence) {
if (sentence == null ||
sentence.trim().isEmpty()) {
return 0;
}
StringTokenizer tokenizer =
new StringTokenizer(sentence);
return tokenizer.countTokens();
}
public static void main(String[] args) {
System.out.println(
countWords("Java Programming Language"));
System.out.println(
countWords("Hello World"));
}
}
Output
3
2
How It Works
StringTokenizer automatically separates words using whitespace delimiters.
Example
Java Programming Language
↓
Java
Programming
Language
Token count = 3
Advantages
- Easy to use
- Doesn't require regex
- Handles multiple spaces automatically
Disadvantages
- Legacy class
- Less flexible than
split()
Time Complexity
O(n)
Space Complexity
O(1)
Method 3: Using Regular Expressions
Regular expressions provide greater control over what is considered a word.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CountWordsRegex {
public static int countWords(String sentence) {
if (sentence == null ||
sentence.trim().isEmpty()) {
return 0;
}
Pattern pattern = Pattern.compile("\\w+");
Matcher matcher = pattern.matcher(sentence);
int count = 0;
while (matcher.find()) {
count++;
}
return count;
}
public static void main(String[] args) {
System.out.println(
countWords("Hello, World! Java."));
}
}
Output
3
How It Works
Regex
\w+
matches
- Letters
- Digits
- Underscores
Each match is counted as one word.
Advantages
- Handles punctuation better
- Flexible
- Easy to customize
Disadvantages
- Regex overhead
- Slightly slower
Time Complexity
O(n)
Space Complexity
O(1)
Method 4: Using Stream API
Java 8 Streams provide a functional programming approach.
import java.util.Arrays;
public class CountWordsStream {
public static long countWords(String sentence) {
if (sentence == null ||
sentence.trim().isEmpty()) {
return 0;
}
return Arrays.stream(sentence.trim().split("\\s+"))
.filter(word -> !word.isEmpty())
.count();
}
public static void main(String[] args) {
System.out.println(
countWords("Spring Boot Framework"));
}
}
Output
3
Advantages
- Modern Java style
- Easy to combine with filters
- Functional programming
Disadvantages
- Extra stream overhead
- Less efficient than simple loops
Time Complexity
O(n)
Space Complexity
O(n)
Method 5: Manual Character Traversal
Instead of splitting the string, count transitions from whitespace to non-whitespace characters.
public class CountWordsManual {
public static int countWords(String sentence) {
if (sentence == null ||
sentence.trim().isEmpty()) {
return 0;
}
int count = 0;
boolean insideWord = false;
for (char ch : sentence.toCharArray()) {
if (Character.isWhitespace(ch)) {
insideWord = false;
} else if (!insideWord) {
count++;
insideWord = true;
}
}
return count;
}
public static void main(String[] args) {
System.out.println(
countWords("Java Programming Language"));
}
}
Output
3
Advantages
- No arrays created
- Memory efficient
- Excellent for very large strings
Disadvantages
- Slightly more code
Time Complexity
O(n)
Space Complexity
O(1)
Performance Comparison
| Method | Time Complexity | Space Complexity | Performance |
|---|---|---|---|
| split() | O(n) | O(n) | ⭐⭐⭐⭐⭐ |
| StringTokenizer | O(n) | O(1) | ⭐⭐⭐⭐ |
| Regex | O(n) | O(1) | ⭐⭐⭐ |
| Streams | O(n) | O(n) | ⭐⭐⭐ |
| Manual Traversal | O(n) | O(1) | ⭐⭐⭐⭐⭐ |
Approximate benchmark
| Method | 100,000 Sentences |
|---|---|
| split() | ~20 ms |
| Manual Traversal | ~22 ms |
| StringTokenizer | ~40 ms |
| Regex | ~60 ms |
| Streams | ~80 ms |
Handling Edge Cases
Empty String
countWords("")
Output
0
Multiple Spaces
countWords("Java Programming")
Output
2
Tabs
countWords("Java\tProgramming")
Output
2
New Lines
countWords("Java\nProgramming")
Output
2
Leading and Trailing Spaces
countWords(" Java Programming ")
Output
2
Practical Examples
Example 1: Count Words After Removing Punctuation
public static int countWords(String sentence) {
String cleaned =
sentence.replaceAll("[^a-zA-Z0-9\\s]", "");
if (cleaned.trim().isEmpty()) {
return 0;
}
return cleaned.trim().split("\\s+").length;
}
Input
Hello, World! Java.
Output
3
Example 2: Count Unique Words
Set<String> uniqueWords =
new HashSet<>(
Arrays.asList(
sentence
.toLowerCase()
.trim()
.split("\\s+")));
System.out.println(uniqueWords.size());
Example 3: Word Frequency
Map<String, Integer> frequency =
new HashMap<>();
for (String word :
sentence.toLowerCase().split("\\s+")) {
frequency.put(
word,
frequency.getOrDefault(word, 0) + 1);
}
Useful for:
- Text analysis
- Search engines
- NLP
Example 4: Reading a File
int totalWords = 0;
for (String line : Files.readAllLines(path)) {
totalWords += countWords(line);
}
Common Mistakes
Mistake 1: Using split(" ")
❌ Wrong
sentence.split(" ");
Multiple spaces create empty strings.
✅ Correct
sentence.split("\\s+");
Mistake 2: Forgetting trim()
Without trimming,
" Hello"
can produce unwanted empty elements.
Always use
sentence.trim()
Mistake 3: Ignoring Null Strings
❌ Wrong
sentence.split("\\s+");
Throws NullPointerException.
✅ Correct
if (sentence == null)
return 0;
Mistake 4: Counting Empty Strings
Always ignore empty tokens.
Best Practices
Use split() for General Applications
Simple, readable, and reliable.
Use Manual Traversal for Maximum Performance
Especially when processing millions of strings.
Validate Input
Always check
- null
- empty string
- whitespace-only string
Normalize Text
Convert multiple spaces into one when needed.
Frequently Asked Questions
Q1: What counts as a word?
Answer: Typically, any sequence of non-whitespace characters separated by whitespace.
Q2: How do I ignore punctuation?
Answer: Remove punctuation first using replaceAll("[^a-zA-Z0-9\\s]", ""), or use a regex that matches only words.
Q3: Which method is the fastest?
Answer: The split() method is fast and convenient for most applications, while manual character traversal offers similar performance with lower memory usage.
Q4: How do I count unique words?
Answer: Store the words in a HashSet and use its size() method.
Q5: What happens with an empty string?
Answer: Return 0 after checking null and trimming whitespace.
Q6: Can I count words in a text file?
Answer: Yes. Read each line from the file, count its words, and sum the results.
Q7: How do I support multiple languages?
Answer: Use Unicode-aware regular expressions such as \\p{L}+ for matching letters from different languages.
Q8: Are all methods O(n)?
Answer: Yes. Each method processes the sentence once, making the overall time complexity linear.
Q9: How do I ignore stop words like "the", "is", and "a"?
Answer: Remove them by comparing each word against a predefined stop-word list before counting.
Q10: Which approach is recommended for interviews?
Answer: The split("\\s+") solution is the most common and easy to explain. For optimization discussions, mention the manual traversal approach as it avoids creating intermediate arrays.