Java Program to Count Number of Vowels in a String

There are five vowels in english alphabet that are a, e, i, o, u. Below I have written a java program that will count the number of vowels in a string. I have used switch case to check for vowels, we can also do this using if statement. If you find any difficulty to understand the logic then you can ask your queries.

Java Program to Count Number of Vowels in a String

import java.util.Scanner;

class CountVowels
{
 public static void main(String...s)
 {
  String str="";
  int count=0;
  Scanner sc=new Scanner(System.in);
  System.out.println("Enter a string:");
  str=sc.nextLine();

  for(int i=0;i<str.length();++i)
  {
   switch(str.charAt(i))
   {
    case 'a':
    case 'A':
    case 'e':
    case 'E':
    case 'i':
    case 'I':
    case 'o':
    case 'O':
    case 'u':
    case 'U': count++;  
   }
  }

  System.out.println("Number of vowels are "+count);
 }
}  

Java Program to Count Number of Vowels in a String

Leave a Comment

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