Java Program to Count the Number of Vowels and Consonants in a String

In this java program, we will learn about how to count the total number of vowels and consonant alphabets in this given string.

In english language, alphabets 'a' 'e' 'i' 'o' 'u' are called Vowels and all other alphabets are called Consonants. Given a string, we have to count the total number of vowels and consonants in this given string and print it on screen as follows:

Input String: TechCrashCourse
Vowels: 5
Consonants: 10

Here is the algorithm to accomplish this task:
  • First of all, convert each alphavet of the string to lowercase using toLowerCase() method for easy comparison.

  • Initialze two int variables vowelCount and consonantCount to zero to keep the count of vowels and consonants in string.

  • Compare each char of the given string to vowels ‘a’, ‘e’, ‘i’, ‘o’, ‘u’ using charAt() method, if a match is found then we increment the vowelCount else increment consonantCount.

To understand this java program, you should have understanding of the following Java programming concepts:


Java Program to Count the Number of Vowels and Consonants in a String

public class VowelConsonantCount {
  public static void main(String[] args) {
    String str;
    int vowelCount= 0, consonantCount = 0;

    Scanner scanner = new Scanner(System.in);
    System.out.println("Enter a String");
    str = scanner.nextLine();

    //Convert all characters to lowercase
    str = str.toLowerCase();

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

      if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
        vowelCount++;
      } else if ((ch >= 'a'&& ch <= 'z')) {
        consonantCount++;
      }
    }
    System.out.println("Vowels: " + vowelCount);
    System.out.println("Consonants: " + consonantCount);
  }
}
Output
Enter a String
TechCrashCourse for Programming
Vowels: 8
Consonants: 20