Count Consonants
Count the number of consonants in a string.
BeginnerTopic: Module 4: String Programs
Java Count Consonants Program
This program helps you to learn the fundamental structure and syntax of Java programming.
import java.util.Scanner;
public class Main {
private static boolean isAlphabet(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
private static boolean isVowel(char c) {
c = Character.toLowerCase(c);
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String s = sc.nextLine();
int count = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (isAlphabet(ch) && !isVowel(ch)) {
count++;
}
}
System.out.println("Consonants: " + count);
sc.close();
}
}Output
Enter a string: hello Consonants: 3
Understanding Count Consonants
We count alphabetic characters that are not vowels.
Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.