Written by Sai Sandeep Thota on February 25, 2014 in Java > Programming

Java Program to count number of Vowels present in a String

GET ALERTS:

Get our Latest updates delivered to your mailbox!

In this article we are going to explain a Java Program to count number of Vowels present in a String. We have previously written this program in C Language, you can read it here.

In this program we have defined a character array and initialized it with the vowels as data items ‘a, e, i, o, u’. Next we are getting the String input and converting into Lowercase characters as we have defined vowels array in lowercase characters. Then we are using two for loops and matching the characters of the string using charAt(index) method to vowels array, if the character of the string is a vowel then we are incrementing the count variable and finally printing the Number of Vowels present.

For example:
Input: Hello.
The number of vowels present in ‘Hello’ is 2.

Download Source Code

Java Program to count number of Vowels present in a String

import java.util.Scanner;

class vowels {
	public static void main(String args[]) {
		String str;
		int count=0;
		char[] vowels = new char[] {'a','e','i','o','u'};
		Scanner get = new Scanner(System.in);
		System.out.println("Enter a String:");
		str = get.nextLine().toLowerCase();
		for(int i=0;i<str.length();i++) {
			for(int j=0;j<5;j++) {
				if((str.charAt(i)) == vowels[j]) {
					count++;
				}
			}
		}
		if(count>1) {
			System.out.println("Number of Vowels present in the given String: "+count);
		}
		else {
			System.out.println("There are no vowels present in the given String!");
		}
	}
}

Output:
Java Program to count number of Vowels present in a String

And Yeah! This is my 100th article 🙂

{ 4 comments… read them below or add one }

sanskriti November 19, 2016 at 1:38 am

It was really helpful thank u so much

Reply

sanskriti November 19, 2016 at 1:39 am

It was really useful n saved my 25 marks in the project

Reply

saivandanapalamani February 4, 2017 at 12:02 pm

import java.util.Scanner;

public class Vowels {

private static Scanner sc;

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int count=0;
String sentance;
System.out.println(“Enter a sentance”);
sc = new Scanner(System.in);
sentance=sc.nextLine();

for (int i = 0; i < sentance.length(); i++) {

char ch = sentance.charAt(i);

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {

count++;

}

}

System.out.println("frequency of Vowels in the sentance : " + count);

}
result:
Enter a sentance
hello madam
Intensity of Vowels in the sentance : 4

Reply

jafarkhan May 5, 2017 at 9:06 pm

my question is like that
write a program in java to accept a string from user by command line argument and display the vowel ?

Reply

Leave a Comment

Previous post:

Next post: