Count the Number of Vowels in a String in Java

In this tutorial, we will explore how to count the number of vowels in a string using Java. We will write a Java program that takes a string as input and returns the count of vowels present in that string. To achieve this, we will utilize the String class and its in-built methods.

Problem Statement

Write a Java program that counts the number of vowels in a given string.

The program should prompt the user to enter a string. Once the string is provided, the program will count the number of vowels present in it. Vowels include the letters ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’ (both lowercase and uppercase).

After counting the vowels, the program will display the total count to the user.

For example, if the user enters the string “Hello World”, the program will count the vowels (e, o, o) and display the output as: “The number of vowels in the string is: 3”

Code Implementation

import java.util.Scanner;   

public class VowelCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); 
System.out.print("Enter a string: ");
    String input = scanner.nextLine();

    int vowelCount = 0;

    input = input.toLowerCase();

    for (int i = 0; i < input.length(); i++) 
{
        char ch = input.charAt(i);
        if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') 
{
            vowelCount++;
        }
    }

    System.out.println("The number of vowels in the string is: " + vowelCount);
}
}

Explanation of the toLowerCase() method

Method Signature:

public String toLowerCase()

The toLowerCase() method does not accept any arguments and returns a new String object with all characters converted to lowercase.

Functionality

The toLowerCase() method iterates over each character of the string and converts any uppercase characters to their corresponding lowercase representation. Characters that are already lowercase or non-alphabetic characters remain unchanged.

Return Value

The toLowerCase() method returns a new String object that represents the original string with all characters converted to lowercase.

Example

String str = "Hello World";
String lowercaseStr = str.toLowerCase();
System.out.println(lowercaseStr); // Output: "hello world"

Important Note

It’s important to note that the toLowerCase() method in Java does not alter the original string directly. Instead, it generates a new string with all characters converted to lowercase. This behavior is due to the immutability of strings in Java, which means they cannot be modified once created. As a result, when using the toLowerCase() method, the original string remains unaffected and unchanged

Conclusion

Counting the number of vowels in a string is a common task in Java programming. By utilizing the String class and the provided code, you can easily determine the count of vowels within any given string. Remember to iterate through each character and check if it matches any of the vowels.

Happy coding !