Count Vowels in a String in Java — Definition, Examples and Program
Counting vowels in a string is a basic string problem that helps beginners understand character comparison, loops, and conditional statements.
In this blog, you will learn:
- What vowels are
- How to count vowels in a string
- Step-by-step examples
- A simple Java program
- Practice challenges
What Are Vowels?
Vowels in the English alphabet are:
a, e, i, o, u
Both uppercase and lowercase vowels should be considered while counting.
How the Logic Works
To count vowels in a string:
- Read the string from the user.
- Traverse each character of the string.
- Check if the character is a vowel.
- Increase the count when a vowel is found.
Example 1
Input: "programming"
- p → not a vowel
- r → not a vowel
- o → vowel (count = 1)
- a → vowel (count = 2)
- i → vowel (count = 3)
Total Vowels: 3
Example 2
Input: "HELLO WORLD"
- E → vowel
- O → vowel
- O → vowel
Total Vowels: 3
Java Program to Count Vowels
import java.util.Scanner;
public class CountVowels {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = sc.nextLine();
int vowelCount = 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') {
vowelCount++;
}
}
System.out.println("Number of vowels: " + vowelCount);
}
}
Sample Output
Enter a string: Education
Number of vowels: 5
Practice Challenges
- Modify the program to count consonants as well.
- Count vowels without converting the string to lowercase.
- Find which vowel appears the most times in a string.
Counting vowels is a simple yet powerful exercise that strengthens your understanding of strings and conditions in Java.