String Java Programs

Java Program to Count Vowels and Consonants in the String

In this tutorial, we are going to learn java programming to count the number of vowels (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) and consonants (any alphabet other than vowels) in a string.

For any input string, we have to count the number of vowels that appear and the number of consonants that appear. And returns the number of vowels and consonants as an output of our program.

For example

Case1: For the input string ‘Python Is Fun’
The output should be the number of vowels that is 3(‘o’, ‘I’, ‘u’) and the number of consonants that is 8(‘P’, ‘y’, ‘t’, ‘h’, ‘n’, ‘s’, ‘F’, ‘n’).

Case 2: For the input string ‘Hitechpoints’
The output should be the number of vowels that is 3(‘i’, ‘e’, ‘o’, ‘i’) and the number of consonants that is 4(‘H’, ‘t’, ‘c’, ‘h’, ‘p’, ‘n’, ‘t’, ‘s’).

Java Program to Count Vowels and Consonants in the String

import java.util.*;

public class Main {

	public static void main(String[] args) {
		ArrayList<Character> arr = new ArrayList<Character>(
				Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));
		int vowel = 0, consonant = 0;
		System.out.println("Java program to count vowel and consonant");
		Scanner sc = new Scanner(System.in);
		System.out.println("Please enter a String");
		String str = sc.nextLine();
		for (int i = 0; i < str.length(); i++) {
			if (arr.contains(str.charAt(i))) {
				vowel++;
			} else if ((str.charAt(i) >= 'a' && str.charAt(i) <= 'z')
					|| (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z')) {
				consonant++;
			}
		}
		System.out.println("Vowel= " + vowel + ", Consonant =" + consonant);
	}
}

Output

Java program to count vowel and consonant
Please enter a String
Hitechpoints Website
Vowel= 7, Consonant =12

Explanation

For the input string ‘Hitechpoints Website’, the string is first iterated through each of each character, and as the vowels ‘u’, ‘e’,‘i’, and ‘o’ are found the variable ‘vowel’ is incremented each time the vowels are found, In this case, the ‘vowel’ variable is incremented 7 times from ‘0’.

Similarly, the variable ‘consonants’ will increment itself each time it encounters a consonant. In this case, the consonant will increment itself 12 times as it found consonants ‘H’, ‘t’, ‘c’, ‘h’, ‘p’, ‘n’, ‘t’, ‘s’, ‘w’, ‘b’, ‘s’ and ‘t’.

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs