</>

Technology

Java Programs

Difficulty

Beginner

Interview Question

Write a Java program to count vowels and consonants in a string.

Answer

Count Vowels and Consonants in a String

Java
public class CountVowelsConsonants {
    public static void main(String[] args) {
        String str     = "Hello World Java Selenium";
        int vowels     = 0;
        int consonants = 0;

        str = str.toLowerCase();

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);

            // Check if character is a letter
            if (ch >= 'a' && ch <= 'z') {
                if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
                    vowels++;
                } else {
                    consonants++;
                }
            }
            // spaces and special chars are skipped
        }

        System.out.println("String:     " + str);
        System.out.println("Vowels:     " + vowels);
        System.out.println("Consonants: " + consonants);
    }
}

Output

CODE
String:     hello world java selenium
Vowels:     9
Consonants: 13

Using String.contains() (Cleaner)

Java
String str     = "Automation Testing";
String vowelSet = "aeiouAEIOU";
int vowels = 0, consonants = 0;

for (char ch : str.toCharArray()) {
    if (Character.isLetter(ch)) {
        if (vowelSet.indexOf(ch) != -1) {
            vowels++;
        } else {
            consonants++;
        }
    }
}

System.out.println("Vowels:     " + vowels);     // 7
System.out.println("Consonants: " + consonants); // 11

Using Java 8 Streams

Java
String str = "Automation Testing";

long vowels = str.toLowerCase().chars()
    .filter(c -> "aeiou".indexOf(c) != -1)
    .count();

long consonants = str.toLowerCase().chars()
    .filter(Character::isLetter)
    .filter(c -> "aeiou".indexOf(c) == -1)
    .count();

System.out.println("Vowels:     " + vowels);     // 7
System.out.println("Consonants: " + consonants); // 11

Using switch Statement

Java
for (char ch : str.toLowerCase().toCharArray()) {
    switch (ch) {
        case 'a': case 'e': case 'i': case 'o': case 'u':
            vowels++;
            break;
        default:
            if (Character.isLetter(ch)) consonants++;
    }
}

Automation Testing Relevance

Java
// Validate that a description field has actual words (not numbers/symbols only)
String description = driver.findElement(By.css(".desc")).getText();
long letterCount = description.chars().filter(Character::isLetter).count();
assertTrue(letterCount > 20, "Description must contain at least 20 letters");

Follow AutomateQA