Java Program to Count Number of Vowels in a String

Java Program to Count Number of Vowels in a String | The alphabets ‘A’, ‘E’, ‘I’, ‘O’, ‘U’ (in uppercase) and ‘a’, ‘e’, ‘i’, ‘o’, ‘u’ are vowels and remaining alphabets are called consonants.

The given String can be in uppercase or lowercase or both, so either we have to write separate logic for both cases or convert the given string to uppercase or lowercase and write logic only for one case.

In the String class, toUpperCase() method is given to convert the given string to uppercase, and toLowerCase() method is given to convert the string to lowercase.

// convert string to uppercase
String str = "KnowProgram@123";
str = str.toUpperCase();

The toUpperCase() method converts “KnowProgram@123” to “KNOWPROGRAM@123”. Therefore, we have to write logic to check only for ‘A’, ‘E’, ‘I’, ‘O’, and ‘U’. The charAt(int i) method of the String class can be used to iterate through each character of the String.

Condition to check character is a vowel or not:-

// in case of uppercase characters
if(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
then it is vowel.
// in case of lowercase characters
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
then it is vowel.

To count the number of vowels in the given String take a “count” variable of int data type and check each character. If any character is a vowel then increase the “count” variable by 1. Finally, the count value has the total number of vowels in the given String.

Program to Count Vowels in Java String

import java.util.Scanner;

public class CountVowels {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int countVowel = 0;

        // read input
        System.out.print("Enter String: ");
        String str = scan.nextLine();

        // convert string to upperCase
        str = str.toUpperCase();

        // check each character
        for (int i = 0; i < str.length(); i++) {
            if (isVowel(str.charAt(i))) {
                countVowel++;
            }
        }

        System.out.println("Number of vowels: " + countVowel);
        scan.close();
    }

    // method to check vowel (only upper case)
    private static boolean isVowel(char ch) {
        if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
            return true;
        }
        return false;
    }

}

Output:-

Enter String: KnowProgram@2025
Number of vowels: 3

Enter String: Hello, How are you?
Number of vowels: 7

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *