Java program to count vowels and consonants in a String

In this simple Java program, learn to find the count of vowels and consonants in a given input string.

1. How to count vowels and consonants in a String

In English alphabets, there are 5 vowels (‘a’, ‘e’, ‘i’, ‘o’ and ‘u’) and rest are consonants.

Please keep in mind that a string in java can have several kind of characters such as :

  • alphabets
  • numbers
  • special characters
  • white spaces etc.

We have to find and count the alphabets in such a way that we can filter out other kind of characters.


Follow given algorithm to count the vowels and consonants separately.

  1. Read an input string
  2. Convert the string to lower case so that comparisons can be reduced
  3. Iterate over it’s characters one by one
  4. If current character matches with vowels (a, e, i, o, u ) then increment the vCount by 1
  5. Else if any character lies between ‘a’ and ‘z’, then increment the count for cCount by 1
  6. Print both the counts

2. Java program to count vowels and consonants in String

package com.howtodoinjava.example;

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(;
		System.out.print("Input string : ");

		// 1
		String str = scanner.nextLine();

		// 2
		str = str.toLowerCase();

		int vCount = 0, cCount = 0;  
		for (int i = 0; i < str.length(); i++) 
			//4. Checks whether a character is a vowel
			if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' 
                               || str.charAt(i) == 'o' || str.charAt(i) == 'u') {
				// Increments the vowel counter
			//5. Checks whether a character is a consonant
			else if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') 
				// Increments the consonant counter
		System.out.println("Number of vowels: " + vCount);
		System.out.println("Number of consonants: " + cCount);

Program output.

Input string : how to do in java

Number of vowels: 6
Number of consonants: 7

Drop me your questions related to program to count the number of vowels and consonants in a given string in Java.

Happy Learning !!


Notify of
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode