Java Program to Count Number of Vowels in a String
In java, the string is a sequence of characters and char is a single digit used to store variables. The char uses 2 bytes in java. In java, BufferedReader and InputStreamReader are used to read the input given by the user from the keyboard. Then readLine() is used for reading a line. The java.io package in java provides input and output through data streams, serialization, and the file system.
We can count the vowels in a string in two ways:
Input: GeeksForGeeks Output: Total no of vowels in string are: 5 Input: ChETaN Output: Total no of vowels in string are: 2
Method 1: Iterative
- We will traverse through the string’s characters in a for loop starting from index 0 till size-1.
- And check each character if it is a vowel or not and increment the count variable.
Total no of vowels in string are: 5
Method 2: Recursive
- Check for the base condition if the length of the string is 1, then simply check for that single character if it is a vowel, then return 1 else return 0.
- For dividing the whole string into substring to return the answer recursively, we will get the answer for the string starting from first till second last character.
- And finally return the above answer plus the answer for the check of last character (1 if it is vowel or 0 if it is not)
Total number of vowels in string are: 6
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.