Count Consonants in a String in Java — Definition, Examples and Program

Learn how to count consonants in a string using Java. This blog explains the concept with examples, a simple Java program, and practice challenges for beginners.

Count Consonants in a String in Java — Definition, Examples and Program

Counting consonants in a string helps beginners understand how to work with characters, conditions, and loops in Java. A consonant is any alphabet character that is not a vowel.

In this blog, you will learn:

What Are Consonants?

Consonants are all alphabet characters except vowels.

Vowels: a, e, i, o, u

Consonants: b, c, d, f, g, h, j, k, l, m, n, p, q, r, s, t, v, w, x, y, z

How the Logic Works

To count consonants in a string:

  1. Read the input string.
  2. Traverse each character of the string.
  3. Check if the character is an alphabet.
  4. Ensure the character is not a vowel.
  5. Increase the consonant count.

Example 1

Input: "programming"

Total Consonants: 8

Example 2

Input: "HELLO WORLD"

Total Consonants: 7

Java Program to Count Consonants


import java.util.Scanner;

public class CountConsonants {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a string: ");
        String input = sc.nextLine();

        int consonantCount = 0;

        input = input.toLowerCase();

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

            if (ch >= 'a' && ch <= 'z') {
                if (ch != 'a' && ch != 'e' && ch != 'i' &&
                    ch != 'o' && ch != 'u') {
                    consonantCount++;
                }
            }
        }

        System.out.println("Number of consonants: " + consonantCount);
    }
}

Sample Output


Enter a string: Education
Number of consonants: 4

Practice Challenges

  1. Modify the program to count vowels, consonants, digits, and spaces separately.
  2. Count consonants without converting the string to lowercase.
  3. Find the most frequent consonant in a string.

Counting consonants strengthens your understanding of character classification and conditional logic in Java. It is a common interview problem and a great stepping stone to advanced string manipulation.