Count the Number of Vowels in a Given String – Java Program

 

 

Count the Number of Vowels in a Given String – Java Program

This Java program counts the number of vowels in a given string. The vowels considered are ‘a’, ‘e’, ‘i’, ‘o’, ‘u’ (both uppercase and lowercase). Below is the complete Java code and an explanation of its structure.

Java Program Code


            /**
             * This class provides a method to count the number of vowels in a given string.
             */
            public class VowelCounter {
                /**
                 * Main method to test the countVowels method.
                 * @param args Command line arguments (not used).
                 */
                public static void main(String[] args) {
                    String input = "Hello World";
                    int vowelCount = countVowels(input);
                    System.out.println("Number of vowels in \"" + input + "\": " + vowelCount);
                }

                /**
                 * Counts the number of vowels in the given string.
                 * @param str The input string to be analyzed.
                 * @return The number of vowels in the input string.
                 */
                public static int countVowels(String str) {
                    int count = 0;
                    String vowels = "aeiouAEIOU";
                    
                    for (int i = 0; i < str.length(); i++) {
                        char ch = str.charAt(i);
                        if (vowels.indexOf(ch) != -1) {
                            count++;
                        }
                    }
                    
                    return count;
                }
            }
        

Explanation

The Java program is structured as follows:

  • Class Definition: The VowelCounter class contains the methods to count vowels.
  • Main Method: The main method is the entry point of the program. It initializes a sample string, calls the countVowels method, and prints the result.
  • countVowels Method: This method takes a string as input and returns the number of vowels in that string. It iterates through each character of the string and checks if it is a vowel by comparing it against a string of vowels "aeiouAEIOU". If a match is found, the vowel count is incremented.

Usage

To use this program, simply copy and paste the code into a Java IDE or a text editor, and run the program. The main method demonstrates the functionality with the string “Hello World”. You can change the input string to test with other examples.

 

Leave a Reply

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