Count Vowels
Java coding interview problem for String Coding: Count Vowels.
Counting vowels is one of the most common beginner-friendly string problems in Java interviews.
Although the problem looks simple, interviewers use it to evaluate several important programming concepts, including:
- String traversal
- Character comparison
- Conditional statements
- Loops
- Character arrays
- Time Complexity
- Unicode awareness
Many advanced string problems are built upon this concept.
Interviewers may ask follow-up questions such as:
- Can you count consonants as well?
- Can you ignore spaces and numbers?
- Can you count uppercase and lowercase vowels?
- Can you solve it using Java Streams?
- Can you solve it without using built-in methods?
Learning multiple approaches helps you answer all these interview variations confidently.
Problem Statement
Given a string, count the total number of vowels present.
The English vowels are:
A E I O U
a e i o u
Return the total number of vowels.
Example 1
Input
Hello
Output
2
Explanation
e
o
Example 2
Input
Java Programming
Output
5
Explanation
a
a
o
a
i
Example 3
Input
Sky
Output
0
What are Vowels?
In English,
there are five vowels.
A
E
I
O
U
Their lowercase forms are
a
e
i
o
u
Every other alphabet is considered a consonant.
Example
Input
Education
Characters
E d u c a t i o n
Vowels
E
u
a
i
o
Count
5
Why Count Vowels is Asked in Interviews?
Although this problem appears easy,
it helps interviewers evaluate whether candidates understand:
- String traversal
- Character processing
- Conditional statements
- Loops
- Character arrays
- Time Complexity
- Edge cases
It also forms the basis for more advanced problems like:
- Count Consonants
- Character Frequency
- Remove Vowels
- Reverse Only Vowels
- Longest Vowel Substring
Real-World Applications
Counting vowels has several practical applications.
Text Analytics
Analyze the composition of text documents.
Natural Language Processing
Calculate language statistics.
Spell Checkers
Many spell-check algorithms analyze vowels and consonants.
Text Compression
Character frequency analysis helps optimize compression.
Search Engines
Search indexing often performs character-level analysis.
Understanding Characters in Java
A Java String consists of individual characters.
Example
String word = "HELLO";
Memory
+---+---+---+---+---+
| H | E | L | L | O |
+---+---+---+---+---+
0 1 2 3 4
Each character has an index.
Example
word.charAt(0)
Output
H
word.charAt(4)
Output
O
ASCII vs Unicode Basics
Java stores characters using Unicode.
Each character has a numeric value.
Example
| Character | Unicode |
|---|---|
| A | 65 |
| E | 69 |
| a | 97 |
| e | 101 |
This allows Java to support multiple languages.
Example
こんにちは
नमस्ते
مرحبا
Most interview problems, however, focus only on English vowels.
Mathematical Concept
Suppose
HELLO
Indexes
0 1 2 3 4
Characters
H E L L O
Traversal
0
↓
1
↓
2
↓
3
↓
4
Count
E
↓
1
O
↓
2
Answer
2
Visual Representation
Input
PROGRAM
P R O G R A M
Traversal
P ✗
R ✗
O ✓
G ✗
R ✗
A ✓
M ✗
Total
2
Dry Run
Input
HELLO
Initial Count
0
Iteration 1
H
↓
Not Vowel
Count
0
Iteration 2
E
↓
Vowel
Count
1
Iteration 3
L
↓
Not Vowel
Count
1
Iteration 4
L
↓
Not Vowel
Count
1
Iteration 5
O
↓
Vowel
Count
2
Final Answer
2
Approach 1 — Using for Loop (Recommended)
This is the most common interview solution.
Traverse the string character by character.
If the current character is a vowel,
increase the counter.
Algorithm
- Initialize count to 0.
- Traverse every character.
- Check whether it is a vowel.
- If yes, increment count.
- Return the final count.
Java Program
public class CountVowels {
public static int countVowels(String input) {
int count = 0;
input = input.toLowerCase();
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (ch == 'a' ||
ch == 'e' ||
ch == 'i' ||
ch == 'o' ||
ch == 'u') {
count++;
}
}
return count;
}
public static void main(String[] args) {
System.out.println(countVowels("Hello"));
System.out.println(countVowels("Java Programming"));
}
}
Output
2
5
Step-by-Step Code Explanation
Initialize counter.
int count = 0;
Convert the string to lowercase.
input = input.toLowerCase();
This avoids checking both uppercase and lowercase vowels separately.
Traverse every character.
for (int i = 0; i < input.length(); i++)
Read one character.
char ch = input.charAt(i);
Check whether it is a vowel.
ch == 'a'
||
ch == 'e'
||
ch == 'i'
||
ch == 'o'
||
ch == 'u'
Increase the counter.
count++;
Return the final answer.
return count;
Dry Run of for Loop
Input
JAVA
| Iteration | Character | Vowel? | Count |
|---|---|---|---|
| 1 | J | No | 0 |
| 2 | A | Yes | 1 |
| 3 | V | No | 1 |
| 4 | A | Yes | 2 |
Final Answer
2
Approach 2 — Using Enhanced for-each Loop
Instead of accessing characters using indexes,
convert the string into a character array.
Then use an enhanced for-each loop.
This approach improves readability.
Algorithm
- Convert the string into a character array.
- Traverse using
for-each. - Check each character.
- Increase the counter whenever a vowel is found.
Java Program
public class CountVowelsForEach {
public static int countVowels(String input) {
int count = 0;
input = input.toLowerCase();
for (char ch : input.toCharArray()) {
if (ch == 'a' ||
ch == 'e' ||
ch == 'i' ||
ch == 'o' ||
ch == 'u') {
count++;
}
}
return count;
}
public static void main(String[] args) {
System.out.println(countVowels("Education"));
}
}
Output
5
Step-by-Step Code Explanation
Convert to lowercase.
input.toLowerCase();
Convert to character array.
input.toCharArray();
Traverse each character.
for (char ch : input.toCharArray())
Check for vowels.
if (ch == 'a' ||
ch == 'e' ||
ch == 'i' ||
ch == 'o' ||
ch == 'u')
Increase the count.
count++;
Return the answer.
return count;
Time & Space Complexity
| Approach | Time | Extra Space |
|---|---|---|
for Loop |
O(n) | O(1) |
Enhanced for-each Loop |
O(n) | O(n)* |
Note: The enhanced
for-eachsolution usestoCharArray(), which creates a new character array. Therefore, it requires O(n) additional space.
Where:
- n = length of the input string.
Comparison of Approaches
| Feature | for Loop |
Enhanced for-each |
|---|---|---|
| Interview Friendly | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
| Easy to Read | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| Extra Space | O(1) | O(n) |
| Uses Index | ✅ | ❌ |
| Production Use | Excellent | Excellent |
Advantages
- Simple and easy to understand.
- Efficient with O(n) time complexity.
- Frequently asked in Java interviews.
- Forms the foundation for many character-processing algorithms.
- Can be extended to count consonants, digits, or special characters.
Drawbacks
- Requires manual comparison of each vowel.
- Does not handle Unicode vowel definitions beyond English.
- Additional preprocessing is needed if only alphabetic characters should be counted.
In Part 2, we'll cover:
- Approach 3 – Using
switchStatement - Approach 4 – Using Java Streams (Java 8+)
- Approach 5 – Using Regular Expressions
- Count Both Vowels and Consonants
- Count Uppercase and Lowercase Vowels
- Unicode Considerations
- Comparison of All Approaches
- Common Interview Mistakes
- Edge Cases
- Frequently Asked Interview Questions
- Related Problems
- Key Takeaways
- Interview Tips
Approach 3 — Using switch Statement
Instead of using multiple if conditions, we can use a switch statement to check whether a character is a vowel.
This approach improves readability and is commonly asked in beginner Java interviews.
Algorithm
- Convert the string to lowercase.
- Traverse every character.
- Use a
switchstatement. - Increment the counter whenever a vowel is found.
- Return the final count.
Java Program
public class CountVowelsSwitch {
public static int countVowels(String input) {
int count = 0;
input = input.toLowerCase();
for (char ch : input.toCharArray()) {
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
count++;
break;
default:
break;
}
}
return count;
}
public static void main(String[] args) {
System.out.println(countVowels("Education"));
}
}
Output
5
Advantages
- Cleaner than multiple
ifconditions. - Easy to extend.
- Readable for beginners.
Drawbacks
- Still requires traversing every character.
- Limited to predefined vowel cases.
Approach 4 — Using Java Streams (Java 8+)
Java Streams provide a modern functional programming approach to process strings.
This solution demonstrates familiarity with the Java Stream API.
Algorithm
- Convert the string to lowercase.
- Create a stream of characters.
- Filter only vowels.
- Count the filtered characters.
Java Program
public class CountVowelsStreams {
public static long countVowels(String input) {
return input
.toLowerCase()
.chars()
.filter(ch ->
ch == 'a' ||
ch == 'e' ||
ch == 'i' ||
ch == 'o' ||
ch == 'u')
.count();
}
public static void main(String[] args) {
System.out.println(countVowels("Java Programming"));
}
}
Output
5
Advantages
- Modern Java style.
- Concise implementation.
- Suitable for functional programming.
Drawbacks
- Slightly slower than simple loops.
- May be less familiar to beginners.
- Usually not preferred in coding interviews unless Java 8+ features are specifically requested.
Approach 5 — Using Regular Expressions
Regular expressions can remove all non-vowel characters.
The remaining string length equals the number of vowels.
Algorithm
- Convert the string to lowercase.
- Remove every non-vowel character.
- Return the remaining string length.
Java Program
public class CountVowelsRegex {
public static int countVowels(String input) {
input = input.toLowerCase();
String vowels = input.replaceAll("[^aeiou]", "");
return vowels.length();
}
public static void main(String[] args) {
System.out.println(countVowels("Education"));
}
}
Output
5
Advantages
- Very short code.
- Easy to understand.
- Demonstrates knowledge of Regular Expressions.
Drawbacks
- Regular expressions are generally slower than simple loops.
- Not the preferred approach for performance-critical applications.
Count Both Vowels and Consonants
Interviewers often extend the problem:
Count both vowels and consonants.
Example
Input
Hello World
Output
Vowels = 3
Consonants = 7
Java Program
public class CountVowelsConsonants {
public static void main(String[] args) {
String input = "Hello World".toLowerCase();
int vowels = 0;
int consonants = 0;
for (char ch : input.toCharArray()) {
if (Character.isLetter(ch)) {
if ("aeiou".indexOf(ch) != -1) {
vowels++;
} else {
consonants++;
}
}
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
}
}
Output
Vowels: 3
Consonants: 7
Count Uppercase and Lowercase Vowels Separately
Sometimes interviewers ask you to count uppercase and lowercase vowels independently.
Example
Input
JaVa PrOgramming
Output
Uppercase Vowels = 2
Lowercase Vowels = 3
Java Program
public class CountUpperLowerVowels {
public static void main(String[] args) {
String input = "JaVa PrOgramming";
int upper = 0;
int lower = 0;
for (char ch : input.toCharArray()) {
if ("AEIOU".indexOf(ch) != -1) {
upper++;
} else if ("aeiou".indexOf(ch) != -1) {
lower++;
}
}
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
}
}
Unicode Considerations
Most interview questions assume English vowels.
However, Java supports Unicode, allowing characters from many languages.
Examples
こんにちは
नमस्ते
مرحبا
The examples in this article count only English vowels:
A E I O U
a e i o u
If your application needs to support vowels from other languages, you must define the vowel set according to the target language and process Unicode code points where appropriate.
Edge Cases
| Input | Expected Output |
|---|---|
"" |
0 |
"A" |
1 |
"BCDF" |
0 |
"12345" |
0 |
"Hello123" |
2 |
"AEIOU" |
5 |
"aeiou" |
5 |
null |
Handle gracefully based on application requirements |
Time & Space Complexity
| Approach | Time | Extra Space |
|---|---|---|
for Loop |
O(n) | O(1) |
Enhanced for-each |
O(n) | O(n) |
switch Statement |
O(n) | O(1) |
| Java Streams | O(n) | O(1)* |
| Regular Expressions | O(n) | O(n) |
Note: Stream operations introduce internal processing overhead. Regular expressions create additional objects during pattern matching and replacement.
Where:
- n = length of the input string.
Comparison of All Approaches
| Approach | Interview Friendly | Readable | Performance |
|---|---|---|---|
for Loop |
⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
Enhanced for-each |
⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
switch Statement |
⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| Java Streams | ⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ |
| Regular Expressions | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ |
Common Interview Mistakes
Mistake 1
Ignoring uppercase vowels.
Wrong
if (ch == 'a')
Correct
input = input.toLowerCase();
or explicitly check both uppercase and lowercase characters.
Mistake 2
Counting numbers and symbols.
Wrong
Hello123!!
Only alphabetic characters should normally be considered.
Use
Character.isLetter(ch)
when needed.
Mistake 3
Using string comparison instead of character comparison.
Wrong
if (ch == "a")
Correct
if (ch == 'a')
Remember:
- Double quotes (
" ") represent aString. - Single quotes (
' ') represent achar.
Mistake 4
Forgetting to initialize the counter.
Wrong
int count;
Correct
int count = 0;
Mistake 5
Not considering an empty string.
Input
""
Output
0
Always test edge cases.
Interview Follow-up Questions
Q1. Count both vowels and consonants.
Q2. Count uppercase and lowercase vowels separately.
Q3. Ignore spaces and special characters.
Q4. Count only unique vowels.
Q5. Which approach is the most efficient?
Q6. Can you solve it using Java Streams?
Q7. Can you solve it using Regular Expressions?
Q8. How would you support Unicode vowels?
Q9. What is the time complexity?
Q10. How would you count vowel frequencies?
Related Problems
- Count Consonants
- Character Frequency
- Remove Vowels from a String
- Reverse Only Vowels
- Reverse String
- Palindrome String
- First Non-Repeating Character
- Longest Substring Without Repeating Characters
- Valid Anagram
Key Takeaways
- Counting vowels is one of the most fundamental string traversal problems.
- A simple
forloop is the preferred interview solution because it is efficient and easy to understand. - A
switchstatement improves readability while maintaining the same time complexity. - Java Streams provide a concise, modern solution but are generally not the first choice in coding interviews.
- Regular Expressions are convenient for text processing but may introduce additional overhead.
- Always consider uppercase letters, special characters, empty strings, and
nullinputs based on the problem requirements.
Frequently Asked Interview Questions
Q1. Which approach is best for interviews?
The for loop or switch statement approach is preferred because it is simple, efficient, and demonstrates a strong understanding of string traversal.
Q2. Why convert the string to lowercase first?
Converting to lowercase avoids checking both uppercase and lowercase vowels separately, simplifying the logic.
Example:
input = input.toLowerCase();
Q3. Can we count vowels without using loops?
Yes. You can use Java Streams or Regular Expressions, but internally each character is still processed.
Q4. Which approach performs the best?
The for loop and switch statement generally provide the best balance of readability and performance with O(n) time and O(1) extra space.
Q5. How can we count the frequency of each vowel?
Use a Map<Character, Integer>.
Example output:
a → 3
e → 2
i → 1
o → 4
u → 0
This is a common follow-up question in interviews.
Interview Tip
If an interviewer asks:
"Count the vowels in a string."
Start with the classic for loop solution.
Explain that:
- Traverse the string one character at a time.
- Convert it to lowercase (or check both cases).
- Compare each character against the five vowels.
- Increment the counter whenever a vowel is found.
- Return the total count.
After solving the basic problem, mention advanced variations such as:
- Counting consonants
- Counting vowel frequencies
- Ignoring spaces and punctuation
- Using Java Streams
- Using Regular Expressions
This demonstrates both strong Java fundamentals and the ability to discuss multiple implementation strategies during interviews.