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

In this tutorial, we will explore how to write a Java program to count the number of vowels and consonants in a sentence.


Vowels are the letters A, E, I, O, and U, while all other letters are consonants.

The program will take a sentence as input and then count the number of vowels and consonants in it.

Here’s the code for the program:

import java.util.Scanner;

public class CountVowelsConsonants {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String sentence = scanner.nextLine();
        int vowels = 0, consonants = 0;

        sentence = sentence.toLowerCase();

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

            if (ch >= 'a' && ch <= 'z') {
                if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
                    ++vowels;
                } else {
                    ++consonants;
                }
            }
        }

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

In the code, we first import the Scanner class from the java.util package to get input from the user.

We then prompt the user to enter a sentence using the System.out.print() statement and store the sentence in a String variable called sentence.

We then initialize two integer variables called vowels and consonants to zero.

We then convert the sentence to lowercase using the toLowerCase() method.

We then iterate through each character of the sentence using a for loop.

We check if the current character is a letter using the ASCII values.

If it is a letter, we then check if it is a vowel or a consonant using an if-else statement.

If it is a vowel, we increment the vowels variable, and if it is a consonant, we increment the consonants variable.

Finally, we print the number of vowels and consonants using the System.out.println() statement.


In conclusion, this program is a simple yet effective way of counting the number of vowels and consonants in a sentence using Java.