English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Arrays

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collections

Java Set Collections

Java Input Output (I/O)/O)

Java Reader/Writer

Java Other Topics

Java program to calculate the number of vowels and consonants in a sentence

Java Examples Comprehensive

In this program, you will learn to use if in Java to calculate the number of vowels, consonants, digits, and spaces in a given sentence.

Example: A program to calculate vowels, consonants, digits, and spaces

public class Count {
    public static void main(String[] args) {
        String line = "This website is aw"3som3.";
        int vowels = 0, consonants = 0, digits = 0, spaces = 0;
        line = line.toLowerCase();
        for (int i = 0; i < line.length(); ++i)
        {
            char ch = line.charAt(i);
            if (ch == 'a' || ch == 'e' || ch == 'i')
                || ch == 'o' || ch == 'u') {
                ++vowels;
            }
            else if ((ch >= 'a' && ch <= 'z')) {
                ++consonants;
            }
            else if (ch >= '0' && ch <= '9')9')
            {
                ++digits;
            }
            else if (ch == ' ')
            {
                ++spaces;
            }
        }
        System.out.println("Vowels: " + vowels);
        System.out.println("Consonant: ", + consonants);
        System.out.println("Number: ", + digits);
        System.out.println("Space: ", + spaces);
    }
}

When running the program, the output is:

Vowel: 6
Consonant: 11
Number: 3
Space: 3

In the above example, each check has4condition.

  • The first if condition is to check if the character isVowel.

  • The else if condition after if is used to check if the character is a consonant. The order should be the same, otherwise, all the vowels are also considered as consonants.

  • The third condition (else if) is to check if the character is into9between.

  • Finally, the last condition is to check if the character isSpaceCharacter.

For this, we use toLowerCase() to make the line lowercase. This is an optimization that does not check uppercase A to Z and vowels.

We use the length() function to know the length of the string, and use the charAt() function to get the character at the given index (position).

Java Examples Comprehensive