Java Program to Count Vowels and Consonants in the String

In this tutorial, we are going to learn java programming to count the number of vowels (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) and consonants (any alphabet other than vowels) in a string.

For any input string, we have to count the number of vowels that appear and the number of consonants that appear. And returns the number of vowels and consonants as an output of our program.

For example

Case1: For the input string ‘Python Is Fun’

The output should be the number of vowels that is 3(‘o’, ‘I’, ‘u’) and the number of consonants that is 8(‘P’, ‘y’, ‘t’, ‘h’, ‘n’, ‘s’, ‘F’, ‘n’).

Case 2: For the input string ‘Quescol’

The output should be the number of vowels that is 3(‘u’, ‘e’, ‘o’) and the number of consonants that is 4(‘Q’, ‘s’, ‘c’, ‘l’).

Java Program to Count Vowels and Consonants in the String

import java.util.*;
public class Main
{
    
    public static void main (String[]args)
    {
        ArrayList<Character> arr = new ArrayList<Character>(Arrays.asList('a','e','i','o','u','A','E','I','O','U'));
        int vowel =0, consonant= 0;
        System.out.println("Java program to count vowel and consonant");
        Scanner sc = new Scanner (System.in);
        System.out.println ("Please enter a String");
        String str = sc.nextLine(); 
        for(int i = 0; i < str.length(); i++){
            if(arr.contains(str.charAt(i))) {        
                vowel++;    
            }    
            else if((str.charAt(i) >= 'a' && str.charAt(i)<='z') || (str.charAt(i) >= 'A' && str.charAt(i)<='Z')) {      
                consonant++;    
            }   
        }    
        System.out.println("Vowel= "+vowel+", Consonant ="+consonant);
    }
}

Output

Java program to count vowel and consonant
Please enter a String
Quescol
Vowel= 3, Consonant =4

Explanation

For the input string ‘Quescol website’, the string is first iterated through each of each character, and as the vowels ‘u’, ‘e’,‘i’, and ‘o’ are found the variable ‘vowel’ is incremented each time the vowels are found, In this case, the ‘vowel’ variable is incremented 6 times from ‘0’.

Similarly, the variable ‘consonants’ will increment itself each time it encounters a consonant. In this case, the consonant will increment itself 8 times as it found consonants ‘Q’, ‘s’, ‘c’, ‘l’, ‘w’, ‘b’, ‘s’ and ‘t’.