Java Program to Count the Number of Vowels and Consonants in a Sentence

In this program, you’ll learn to count the number of vowels, consonants, digits and spaces in a given sentence using if else in Java.

Example: Program to count vowels, consonants, digits and spaces

  1. public class Count {
  2. public static void main(String[] args) {
  3. String line = "This website is aw3som3.";
  4. int vowels = 0, consonants = 0, digits = 0, spaces = 0;
  5. line = line.toLowerCase();
  6. for(int i = 0; i < line.length(); ++i)
  7. {
  8. char ch = line.charAt(i);
  9. if(ch == 'a' || ch == 'e' || ch == 'i'
  10. || ch == 'o' || ch == 'u') {
  11. ++vowels;
  12. }
  13. else if((ch >= 'a'&& ch <= 'z')) {
  14. ++consonants;
  15. }
  16. else if( ch >= '0' && ch <= '9')
  17. {
  18. ++digits;
  19. }
  20. else if (ch ==' ')
  21. {
  22. ++spaces;
  23. }
  24. }
  25. System.out.println("Vowels: " + vowels);
  26. System.out.println("Consonants: " + consonants);
  27. System.out.println("Digits: " + digits);
  28. System.out.println("White spaces: " + spaces);
  29. }
  30. }

When you run the program, the output will be:

Vowels: 6
Consonants: 11
Digits: 3
White spaces: 3

In the above example, we’ve 4 conditions for each of the checks.

  • The first if condition is to check whether the character is a vowel or not.
  • The else if condition following if is to check whether the character is a consonant or not. The order should be the same otherwise, all vowels are treated as consonants as well.
  • The 3rd condition (else-if) is to check whether the character is between 0 to 9 or not.
  • Finally, the last condition is to check whether the character is a space character or not.

For this, we’ve lowercased the line using toLowerCase(). This is an optimization done not to check for capitalized A to Z and vowels.

We’ve used length() function to know the length of the string and charAt() to get the character at the given index (position).