Misc-Java-Examples

How to count the number of vowels and consonants in a String

Posted On
Posted By admin

In this blog post, I will be demonstrating a Java program that counts the number of vowels and consonants in a String.

Consider the following code sample:

public class CountVowelsAndConsonantsDemo {
  
  private static List<Character> vowels = Arrays.asList('a','e','i','o','u','A','E','I','O','U');

  public static void main(String[] args) {
    System.out.println("Enter a String:");
    Scanner scanner = new Scanner(System.in); 
    String input = scanner.nextLine();
    char[] inputArr = input.toCharArray();
    int vowelCount = 0;
    int consonantCount = 0;
    for(char c:inputArr){
      if(vowels.contains(c)){
        vowelCount++;
      }
      else
        consonantCount++;
    }
    System.out.println("Number of vowels:"+vowelCount);
    System.out.println("Number of consonants:"+consonantCount);

  }

}

 

The code declares and initalizes a list ‘vowels’ with all the vowels in lowercase and uppercase. It then iterates through the characters in the input String. It checks if each character is present in the vowels list, if so it increments the vowels counter, otherwise it increments the consonants counter.

When you run this code, it will print the following output:

Enter a String:
HELLO
Number of vowels:2
Number of consonants:3
If you'd like to watch a detailed video tutorial of this topic or other related topics, do check out my Java course here

Also, if you'd like to test your Java knowledge, do check out my practice tests course here


If you like this post, please do let me know via the comments box below.  You can also connect with me via my Facebook Page or subscribe to my Youtube channel!

Related Post

leave a Comment