Java Program to count number of vowels and consonants in a string


In this program, You will learn how to count number of vowels and consonants in a string in Java.


Learn Java

vowels = 4

consonants = 5


Example: How to count number of vowels and consonants in a string in Java

Run it Now
import java.util.Scanner;

class Main {
    public static void main(String args[]) {

        int i = 0, vols = 0, cons = 0;
        int size;
        String val;
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a String Value :");
        val = sc.nextLine();

        size = val.length();
        char str[] = val.toCharArray();

        while (i < size) {
            if (str[i] == 'a' || str[i] == 'e'
                    || str[i] == 'i' || str[i] == 'o'
                    || str[i] == 'u' || str[i] == 'A'
                    || str[i] == 'E' || str[i] == 'I'
                    || str[i] == 'O' || str[i] == 'U') {
                vols++;
            } else if (str[i] >= 'A' && str[i] <= 'Z' || str[i] >= 'a' && str[i] <= 'z') {
                cons++;
              }
            i++;
        }

        System.out.print("\nTotal Vowels is :" + vols);
        System.out.print("\nTotal Consonants is :" + cons);
    }
}

Output:

Enter a String Value :Learn Java
Total Vowels is :4
Total Consonants is :5