Start Coding Now
📝 String Programsbeginner1 methods

Count Vowels and Consonants in String

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

Last updated: 11 January 2026

Method 1: Using Loop and If

Iterate character by character.

public class CountVowels {
    public static void main(String[] args) {
        String line = "This is a simple sentence";
        int vowels = 0, consonants = 0, digits = 0, spaces = 0;

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

            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
                ++vowels;
            } else if ((ch >= 'a' && ch <= 'z')) {
                ++consonants;
            } else if (ch >= '0' && ch <= '9') {
                ++digits;
            } else if (ch == ' ') {
                ++spaces;
            }
        }

        System.out.println("Vowels: " + vowels);
        System.out.println("Consonants: " + consonants);
        System.out.println("Digits: " + digits);
        System.out.println("White spaces: " + spaces);
    }
}
Output:
Vowels: 8
Consonants: 12
Digits: 0
White spaces: 4

Explanation

Check each character if it matches vowel, consonant (a-z), digit (0-9) or space.

Frequently Asked Questions

Try This Program

Copy this code and run it in our free online Java compiler.

Open Java Compiler