0
0
JavaProgramBeginner · 2 min read

Java Program to Count Vowels and Consonants

Use a Java program that loops through each character of a string, checks if it is a vowel with if ("aeiou".indexOf(Character.toLowerCase(ch)) != -1), and counts vowels and consonants accordingly.
📋

Examples

Inputhello
OutputVowels: 2 Consonants: 3
InputJava Programming
OutputVowels: 5 Consonants: 11
Input12345!@
OutputVowels: 0 Consonants: 0
🧠

How to Think About It

To count vowels and consonants, read each character of the input string one by one. Convert it to lowercase to simplify checks. If the character is a letter, check if it is one of the vowels (a, e, i, o, u). If yes, increase the vowel count; if not, increase the consonant count. Ignore any characters that are not letters.
📐

Algorithm

1
Get the input string from the user.
2
Initialize vowel and consonant counters to zero.
3
For each character in the string:
4
Convert the character to lowercase.
5
Check if it is a letter.
6
If it is a vowel, increment vowel count.
7
Else if it is a consonant, increment consonant count.
8
After the loop, print the counts of vowels and consonants.
💻

Code

java
import java.util.Scanner;

public class VowelConsonantCounter {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String input = scanner.nextLine();
        int vowels = 0, consonants = 0;
        for (char ch : input.toCharArray()) {
            char lower = Character.toLowerCase(ch);
            if (Character.isLetter(lower)) {
                if ("aeiou".indexOf(lower) != -1) {
                    vowels++;
                } else {
                    consonants++;
                }
            }
        }
        System.out.println("Vowels: " + vowels);
        System.out.println("Consonants: " + consonants);
        scanner.close();
    }
}
Output
Enter a string: hello Vowels: 2 Consonants: 3
🔍

Dry Run

Let's trace the input "hello" through the code

1

Input received

input = "hello"

2

Initialize counters

vowels = 0, consonants = 0

3

Check character 'h'

lower = 'h', isLetter = true, vowel check = false, consonants = 1

4

Check character 'e'

lower = 'e', isLetter = true, vowel check = true, vowels = 1

5

Check character 'l'

lower = 'l', isLetter = true, vowel check = false, consonants = 2

6

Check character 'l'

lower = 'l', isLetter = true, vowel check = false, consonants = 3

7

Check character 'o'

lower = 'o', isLetter = true, vowel check = true, vowels = 2

8

Print results

Vowels: 2, Consonants: 3

CharacterIs LetterIs VowelVowels CountConsonants Count
htruefalse01
etruetrue11
ltruefalse12
ltruefalse13
otruetrue23
💡

Why This Works

Step 1: Check each character

The program looks at each character in the string one by one to decide if it is a vowel or consonant.

Step 2: Use lowercase for easy comparison

Converting characters to lowercase helps to check vowels without worrying about uppercase letters.

Step 3: Count vowels and consonants

If the character is a letter and found in the vowel list, increase vowel count; otherwise, increase consonant count.

🔄

Alternative Approaches

Using switch-case for vowel check
java
import java.util.Scanner;

public class VowelConsonantCounterSwitch {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String input = scanner.nextLine();
        int vowels = 0, consonants = 0;
        for (char ch : input.toCharArray()) {
            char lower = Character.toLowerCase(ch);
            if (Character.isLetter(lower)) {
                switch (lower) {
                    case 'a': case 'e': case 'i': case 'o': case 'u':
                        vowels++;
                        break;
                    default:
                        consonants++;
                }
            }
        }
        System.out.println("Vowels: " + vowels);
        System.out.println("Consonants: " + consonants);
        scanner.close();
    }
}
Switch-case can be clearer for vowel checks but is longer to write.
Using regex to filter letters first
java
import java.util.Scanner;

public class VowelConsonantCounterRegex {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a string: ");
        String input = scanner.nextLine().toLowerCase().replaceAll("[^a-z]", "");
        int vowels = 0, consonants = 0;
        for (char ch : input.toCharArray()) {
            if ("aeiou".indexOf(ch) != -1) {
                vowels++;
            } else {
                consonants++;
            }
        }
        System.out.println("Vowels: " + vowels);
        System.out.println("Consonants: " + consonants);
        scanner.close();
    }
}
Filtering letters first simplifies the loop but uses extra memory for the filtered string.

Complexity: O(n) time, O(1) space

Time Complexity

The program checks each character once, so time grows linearly with input size.

Space Complexity

Only a few counters and variables are used, so space is constant regardless of input size.

Which Approach is Fastest?

The direct character check with indexOf is fast and uses minimal memory compared to regex filtering.

ApproachTimeSpaceBest For
Direct character check with indexOfO(n)O(1)Simple and efficient for all inputs
Switch-case vowel checkO(n)O(1)Clearer logic but more code
Regex filtering then countO(n)O(n)When you want to clean input first
💡
Convert characters to lowercase before checking to simplify vowel detection.
⚠️
Counting non-letter characters as vowels or consonants instead of ignoring them.