Count Vowels in Java: Solution, Explanation & Practice
Count vowels in a string
Problem summary
Write a program that counts all vowels (a, e, i, o, u) in a string.
Starter code
public class Main {
public static void main(String[] args) {
String text = "Hello World"; // Test case 1
// Count vowels (case insensitive)
// Print: Vowel count: <result>
}
}Expected output and test cases
- e, o, o in Hello World
Vowel count: 3
- All vowels once
Vowel count: 5
- No vowels
Vowel count: 0
Hints
- Check each character against vowels
- Use toLowerCase() for case insensitive
- Can use indexOf or contains on vowel string
Validated solution
Reveal Java solution
public class Main {
static int vowelCount(String text) {
int count = 0;
for (char ch : text.toLowerCase().toCharArray()) {
if ("aeiou".indexOf(ch) >= 0) count++;
}
return count;
}
public static void main(String[] args) {
System.out.println("Vowel count: " + vowelCount("Hello World"));
}
}How to approach the problem
Normalize case once, then test every character against the five-vowel set. This keeps the rule visible and avoids a long chain of repeated comparisons.
Approach
- Choose whether y counts as a vowel; this exercise does not.
- Normalize case.
- Increment only for a recognized vowel.
Time and space complexity
Time: O(n). Space: O(n) for toLowerCase; O(1) extra with per-character case checks.
Edge cases to test
- The empty string has zero vowels.
- Locale-specific case rules matter for general text processing.
Common mistakes
- Counting only lowercase letters.
- Using contains on a one-character String without considering unnecessary allocations.
Follow-up challenge
Return a frequency map for each vowel rather than one total.
Related Strings exercises
Practice all Strings exercises · Run this idea in the Java compiler