Java Program to Count Vowels and Consonants in a String

To count vowels and consonants in a Java string, examine each alphabetic character and determine whether it is one of the vowels a, e, i, o, or u. Increment the vowel counter when it is a vowel; otherwise, increment the consonant counter.

For example, the string apple is fruit. contains 5 vowels and 7 consonants. The space and period are not letters, so they should not be included in either count.

In this tutorial, we first use a for loop to count vowels and consonants. We then look at versions that accept input with Scanner, avoid regular expressions, count spaces separately, and use a switch statement for vowel detection.

Count Vowels and Consonants in a Java String using a For Loop

Algorithm to Count Vowels and Consonants in the String

We shall use the following algorithm to write Java program for counting vowels and consonants in the string.

  1. Start.
  2. Read input string to a variable str, or initialize the variable with a string constant.
  3. Transform input string to lower case and replace any character other than alphabet with an empty string. Store the resulting string in alpha.
  4. Initialize vowels with 0 and consonants with 0. These are the counters for vowels and consonants respectively in the string.
  5. For each character in alpha, check if the character is vowel. If true, increment vowels, else increment consonants.
  6. vowels has the count for number of vowels in the string, and consonants have the count for number of consonants in the string.
  7. Stop.

Java Program

</>
Copy
/**
 * Java Program - Count Vowels and Consonants
 */

public class CountVowelConsonant {

	public static void main(String[] args) {

		String str = "apple is fruit.";
		
		String alpha = str.toLowerCase().replaceAll("[^a-z]", "");
		
		int vowels = 0;
		int consonants = 0;
		
		for (char ch: alpha.toCharArray()) {
			if(ch == 'a' || ch=='e' || ch == 'i' || ch=='o' || ch == 'u')
				vowels++;
			else
				consonants++;
		}
		
		System.out.println("Vowels : "+vowels);
		System.out.println("Consonants : "+consonants);
	}
}

Output

Vowels : 5
Consonants : 7

The expression str.toLowerCase() makes the comparison case-insensitive. The call to replaceAll("[^a-z]", "") removes spaces, digits, punctuation, and other non-ASCII-letter characters before counting. Every remaining character is therefore either one of the five vowels checked by the if condition or a consonant.

Java Program to Count Vowels and Consonants using Scanner Input

If the string should be entered at runtime, use Scanner and read the complete line with nextLine(). In this version, non-letter characters are ignored directly inside the loop instead of being removed beforehand.

</>
Copy
import java.util.Scanner;

public class CountVowelsConsonants {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a string: ");
        String str = scanner.nextLine().toLowerCase();

        int vowels = 0;
        int consonants = 0;

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

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

        System.out.println("Vowels : " + vowels);
        System.out.println("Consonants : " + consonants);

        scanner.close();
    }
}

For the input Hello World, the letters e, o, and o are vowels. The remaining seven letters are consonants, while the space is ignored.

Enter a string: Hello World
Vowels : 3
Consonants : 7

Count Vowels and Consonants in Java without replaceAll()

You do not need to create a second string or use a regular expression to solve the problem. You can inspect each character of the original string, convert it to lowercase, and count it only when it is between a and z.

</>
Copy
public class CountVowelsConsonants {
    public static void main(String[] args) {
        String str = "Java Programming 123";

        int vowels = 0;
        int consonants = 0;

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

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

        System.out.println("Vowels : " + vowels);
        System.out.println("Consonants : " + consonants);
    }
}
Vowels : 5
Consonants : 10

The digits and the space are skipped because they do not satisfy the alphabetic range check. This keeps them from being incorrectly counted as consonants.

Count Vowels, Consonants, and Spaces in a Java String

If spaces are also required in the result, keep a separate counter for them. Check for a space before checking whether the current character is a letter.

</>
Copy
public class CountCharacters {
    public static void main(String[] args) {
        String str = "Java is simple";

        int vowels = 0;
        int consonants = 0;
        int spaces = 0;

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

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

        System.out.println("Vowels : " + vowels);
        System.out.println("Consonants : " + consonants);
        System.out.println("Spaces : " + spaces);
    }
}
Vowels : 5
Consonants : 7
Spaces : 2

This example counts literal space characters. Tabs, line breaks, and other whitespace characters are not included in the spaces counter.

Count Vowels and Consonants in Java using switch

A switch statement can also be used to identify vowels. Each vowel case increments the vowel counter, while other alphabetic characters are counted as consonants.

</>
Copy
public class CountWithSwitch {
    public static void main(String[] args) {
        String str = "Education".toLowerCase();

        int vowels = 0;
        int consonants = 0;

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

            if (ch >= 'a' && ch <= 'z') {
                switch (ch) {
                    case 'a':
                    case 'e':
                    case 'i':
                    case 'o':
                    case 'u':
                        vowels++;
                        break;
                    default:
                        consonants++;
                }
            }
        }

        System.out.println("Vowels : " + vowels);
        System.out.println("Consonants : " + consonants);
    }
}
Vowels : 5
Consonants : 4

How the Java Vowel and Consonant Counter Handles Different Characters

CharacterClassification in these examples
a, e, i, o, uVowels
Other letters from a to zConsonants
Uppercase English lettersConverted to lowercase before classification
DigitsIgnored
PunctuationIgnored
SpacesIgnored unless a separate space counter is used

The examples on this page classify the five standard English vowel letters and the remaining English alphabet letters. If a program needs to process letters from other writing systems or language-specific vowel rules, the classification logic should be designed for those requirements rather than relying on the a-to-z checks shown here.

Common Mistakes When Counting Vowels and Consonants in Java

  • Counting every non-vowel as a consonant: spaces, digits, and punctuation are not consonants. Verify that a character is a letter before incrementing the consonant counter.
  • Ignoring uppercase vowels: normalize the string or individual character to lowercase, or explicitly test both cases.
  • Using only next() with Scanner for a sentence: next() stops at whitespace. Use nextLine() when the input may contain spaces.
  • Forgetting to initialize counters: initialize both vowel and consonant counters to 0 before starting the loop.
  • Changing the counter in the wrong branch: increment vowels only for vowel letters and consonants only for other letters.

Java Vowel and Consonant Counting Summary

In this Java Tutorial, we learned how to count vowels and consonants in a given string.