Program to count the number of vowels and consonants in a given string in java: Guys who are serious about learning the concepts of the java programming language should practice this list of programs in java and get a good grip on it for better results in exams or interviews.
Program to Count the Number of Vowels and Consonants in a Sentence
Count vowels in a string java: In this article we will see multiple ways to count total number of vowels and consonants in a sentence in Java.
We know English alphabet consists of 26 letters. These alphabets are sub-divided into two parts i.e. Vowels and Consonants.
- Vowels:- The letters ‘a’, ‘e’, ‘i’, ‘o’ & ‘u’ are considered as vowels in English
- Consonants:- Except vowels, all the remaining letters are considered as consonants in English.
Our task is to count total number of vowels and consonants in English. We will see different approaches to achieve it in Java.
Let’s see the approaches one by one.
Method-I :- By using For loop
In this method we will take a FOR loop and iterate through it. Initially we will convert all characters of String to lowercase as we will don’t have to check for A to Z.
Wherever consonant is found we will increment a variable say vow and wherever vowel is found we will increment a variable say cons. Finally cons and vow is printed which gives total number of consonants and vowels respectively.
Approach:
- Declare a String variable say
str
. - Declare and initialize variable say
vow
,cons
to 0. - Store a English sentence in str.
- Convert the characters into lower case and store in
str
. - Take a for loop and iterate till the length of the string.
- Inside for loop implement the following.
- Declare a variable say temp, with each iteration store a character in temp.
- Taking if condition check whether any character equals to a/e/i/o/u. If yes increment vow.
- Otherwise if character is a letter and does not satisfy above if condition, increment cons.
- After loop execution ends i.e. all characters of the string are checked, print cons and vow.
Program:
public class Main { public static void main(String[] args) { String str = "India is my country."; int vow = 0; int cons = 0; // convert the whole string to lowercase str = str.toLowerCase(); // iterate loop till length of the string for (int i = 0; i < str.length(); ++i) { // store character in temp char temp = str.charAt(i); // check each character is vowel or not if (temp == 'a' || temp == 'e' || temp == 'i' || temp == 'o' || temp == 'u') { ++vow; } // check if there is any character other than vowels else if ((temp >= 'a' && temp <= 'z')) { ++cons; } } System.out.println("Vowels = " + vow); System.out.println("Consonants = " + cons); } }
Output: Vowels = 6 Consonants = 10
Method-II :- By using User-defined input
java.util
package provide Scanner class which asks user to enter he inputs.
This method is almost similar to Method-I. But we only have to ask the user to enter a input (sentence in this case). Then proceed similarly as approach of Method-I.
Approach
- Import Scanner class from
java.util package
. - Declare and initialize variable say
vow
,cons
to 0. - Make instance of Scanner class.
- Declare and String variable say
str
- Ask user to enter a sentence, that will be stored in
str
- Convert the characters into lower case and store in
str
- Take a for loop and iterate till the length of the string.
- Inside for loop implement the following.
- Declare a variable say temp, with each iteration store a character in temp.
- Taking if condition check whether any character equals to a/e/i/o/u. If yes increment vow.
- Otherwise if character is a letter and does not satisfy above if condition, increment cons.
- After loop execution ends i.e. all characters of the string are checked, print cons and vow.
Program:
import java.util.Scanner; public class Main { public static void main(String args[]) { int vow = 0, cons=0; // Ask user to enter a string System.out.println("Please enter a sentence :"); Scanner sc = new Scanner(System.in); // string entered will be stored in str String str = sc.nextLine(); // convert the whole string to lowercase str = str.toLowerCase(); // iterate loop till length of string for (int i=0 ; i<str.length(); i++) { char temp = str.charAt(i); // check if character is a vowel if(temp == 'a'|| temp == 'e'|| temp == 'i' ||temp == 'o' ||temp == 'u') { vow ++; } // check if there is any character other than vowels else if ((temp >= 'a' && temp <= 'z')) { ++cons; } } System.out.println("Vowels = "+vow); System.out.println("Consonants = "+cons); } }
Output Please enter a sentence : India is my country Vowels = 6 Consonants = 10
Method-III :- By using Recursive methods
In this approach we will recursively check for vowels and count those using recursive methods. Similarly, we will recursively check for consonants and count those using recursive methods.
Approach:
- Create a recursive method say
checkCons
which will convert each character to upper string and checks if the characters are consonant or not. - If yes, it will return to
countCons
method where it will recursively count the returned characters fromcheckCons
method. - It will iterate a variable say count and after the end of execution of
countCons
method it will return final value of count to main function. - print the total no. of constants.
- For vowels, take a method say
checkVowel
which checks if character is vowel or not. - If yes, pass it to
countVowel
where it counts the no of characters returned fromcountVowel
in each recursion. - After no value is returned from
checkVowel
return the final value to the main method. - Print the total no. of vowels.
Program:
public class Main { // Function to whether the character is a consonant static boolean checkCons(char temp) { // To handle lower case temp = Character.toUpperCase(temp); // if character is consonant return it return !(temp == 'A' || temp == 'E' || temp == 'I' || temp == 'O' || temp == 'U') && temp >= 65 && temp <= 90; } static int countCons(String str) { int count = 0; for (int i = 0; i < str.length(); i++) // check if the character is consonant by passing it to chekCons if (checkCons(str.charAt(i))) // if charcater found to be consonant increment count value ++count; // total no of consonants in the string passed to main method return count; } // method that check if the character is vowel or not static int checkVowel(char ch) { // if character is vowel return 1 if (ch == 'a' || ch== 'e' || ch== 'i' || ch == 'o' || ch== 'u') { return 1; } else { return 0; } } // recursive function that returns total no of characters in string static int countVowel(String str, int n) { // if (n == 1) { return checkVowel(str.charAt(n - 1)); } // with each call adds total no of vowel if any found in checkVowel method return countVowel(str, n - 1) + checkVowel(str.charAt(n - 1)); } // Driver code public static void main(String args[]) { String str = "India is my country"; // convert string to lower case and stores in str str = str.toLowerCase(); System.out.println("Consonants = "+ countCons(str)); System.out.println("Vowels = "+countVowel(str, str.length())); } }
Output: Consonants = 10 Vowels = 6
Understand the Programming Language Java and learn the language fastly by using our wide range of Java Programming Examples with Output and try to write programs on your own.
Related Java Decision Making and Loop Programs:
- Java Program to Check Leap Year
- Java Program to Check Whether a Number is Positive or Negative
- Java Program to Check Whether a Character is Alphabet or Not
- Java Program to Calculate the Sum of Natural Numbers
- Java Program to Find Factorial of a Number
- Java Program to Generate Multiplication Table
- Java Program to Find GCD of two Numbers
- Java Program to Find LCM of two Numbers
- Java Program to Display Alphabets (A to Z) using loop
- Java Program to Count Number of Digits in an Integer
- Java Program to Check Palindrome
- Java Program to Check Whether a Number is Prime or Not
- Java Program to Check Armstrong Number
- Java Program to Display Armstrong Number Between Two Intervals
- Java Program to Make a Simple Calculator Using switch…case
- Java Program to Sort Elements in Lexicographical Order (Dictionary Order)