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 consonants are
- How to count consonants in a string
- Step-by-step examples
- A simple Java program
- Practice challenges
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:
- Read the input string.
- Traverse each character of the string.
- Check if the character is an alphabet.
- Ensure the character is not a vowel.
- Increase the consonant count.
Example 1
Input: "programming"
- Vowels: o, a, i → 3
- Total letters: 11
- Consonants: 11 − 3 = 8
Total Consonants: 8
Example 2
Input: "HELLO WORLD"
- Ignore space
- Vowels: E, O, O → 3
- Consonants: H, L, L, W, R, L, D → 7
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
- Modify the program to count vowels, consonants, digits, and spaces separately.
- Count consonants without converting the string to lowercase.
- 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.