Count vowels and consonants in a given string

Write a Java program to count the number of vowels and consonants in a given string.

The provided Java program counts the number of vowels and consonants in a given string.

class Main {
    public static void main(String[] args) {
        String str = "Hello";
        countVowelAndConsonant(str);
    }

    public static void countVowelAndConsonant(String str) {
        int vowel = 0;
        int consonant = 0;

        // Convert the string to lowercase for case-insensitive comparison
        str = str.toLowerCase();

        // Loop through each character in the string
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);

            // Check if the character is a vowel
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
                vowel++;
            } 
            // Check if the character is a consonant (it must be a letter)
            else if (ch >= 'a' && ch <= 'z') {
                consonant++;
            }
        }

        // Print the results
        System.out.println("Vowel count: " + vowel);
        System.out.println("Consonant count: " + consonant);
    }
}

Output:

Vowel count: 2
Consonant count: 3

How It Works

  1. Input String:
    • The input string is “Hello”.
  2. countVowelAndConsonant Method:
    • The method takes the string as input, converts it to lowercase for case-insensitive processing, and initializes counters for vowels and consonants.
    • It then loops through each character in the string, checking if it is a vowel (a, e, i, o, u) or a consonant (alphabetical characters that are not vowels).
    • The counters for vowels and consonants are updated accordingly.

Execution:

  1. Convert the string to lowercase: “hello”
  2. Loop through each character:
    • ‘h’ is a consonant → consonant count becomes 1
    • ‘e’ is a vowel → vowel count becomes 1
    • ‘l’ is a consonant → consonant count becomes 2
    • ‘l’ is a consonant → consonant count becomes 3
    • ‘o’ is a vowel → vowel count becomes 2
  3. Final counts:
    • Vowel count: 2
    • Consonant count: 3

Advantages

  • Case-insensitive: The program handles both uppercase and lowercase characters by converting the string to lowercase.
  • Handles non-alphabet characters: Only alphabetical characters are considered consonants or vowels, ignoring spaces and punctuation.

Leave a Reply