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


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


Learn Java

vowels = 4

consonants = 5

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

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.println("Total Vowels are:" + vols);
        System.out.print("Total Consonants are:" + cons);
    }
}

Output:

Enter a string value:Xiith
Total Vowels are:2
Total Consonants are:3

Xiith is created for educational, experimental, and schooling purpose. Examples on Xiith are made easier to make a better or basic understanding. Tutorials, testimonials, and examples are continuously checked to avoid delusion, but we cannot take complete responsibility of all programs on Xiith. When you are operating this site, you have to agree to read and accept our terms of use, cookie and privacy policy.Copyright © 2020 by Xiith. All Rights Reserved. About us.