Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to count total vowels in a String.

Java Code Example — String Programs

ADVERTISEMENT

Java Program to count total vowels in a String.

Objective

Write a Java program to count the total number of vowels in a given string.

Algorithm / Approach

  1. Prompt the user to enter a string and store it.
  2. Initialize a count variable to 0.
  3. Start a for loop from 0 to length() - 1.
  4. Extract the character at the current index using charAt(i).
  5. Use an if condition to check if the character matches any vowel (A, E, I, O, U, a, e, i, o, u).
  6. If it matches, increment the count.
  7. Print the final count.
Test.java
import java.util.Scanner;
class Test {
 public static void main(String[] a)
 {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter String: ");
  String s1 = s.nextLine();
  char x;
  int count=0;
  for(int i=0; i< s1.length(); i++) 
  {
   x = s1.charAt(i);
   if(x=='A' ||x=='E'||x=='I'||x=='O'
   ||x=='U'||x=='a'||x=='e'||x=='i'
   ||x=='o'||x=='u') {
    count++;
   }
  }
  System.out.print("Vowels = "+count);
 }
}

Expected Output

Enter String: Java Prowess
Vowels = 4

Explanation of the Program

  • The charAt() method is crucial here. It allows us to process the string character by character, much like navigating an array.
  • The if statement uses the logical OR (||) operator to check against all 10 possible vowel characters (5 uppercase + 5 lowercase).
  • Alternatively, you could convert the entire string to lowercase first using toLowerCase() to halve the number of comparisons needed in the if statement.

Complexity

Time Complexity O(n) - Where n is the length of the string.
Space Complexity O(1)

Common Mistakes

  • Using double quotes ("A") instead of single quotes ('A') in the if condition. charAt() returns a primitive char, which must be compared using single quotes.
ADVERTISEMENT