Summary

Learn how to count the number of vowels and consonants in a string using Java. Step-by-step explanation with easy-to-understand code and complete logic for Java beginners.

Article Body

Efficient Java Program to Count Vowels and Consonants in a String – Simple Guide for Beginners
Efficient Java Program to Count Vowels and Consonants in a String – Simple Guide for Beginners

When working with strings in Java, one common beginner-level task is to count the number of vowels and consonants in a given string. This simple program helps you understand loops, conditions, and character checking in Java.

Let’s break down the problem and build the solution step-by-step in plain English.


πŸ” What is a Vowel and a Consonant?

In the English alphabet:

  • Vowels are: A, E, I, O, U (both lowercase and uppercase)

  • Consonants are all the other letters except vowels (like B, C, D, F...)

We will ignore digits, spaces, and special characters in our count.


πŸ› οΈ Problem Statement

Input: A string from the user (e.g., β€œHello World”)
Output: Count of vowels and consonants in the string


βœ… Java Code to Count Vowels and Consonants

import java.util.Scanner;

public class VowelConsonantCounter {
    public static void main(String[] args) {
        // Step 1: Create Scanner object to take input from user
        Scanner scanner = new Scanner(System.in);
        
        // Step 2: Ask the user to enter a string
        System.out.print("Enter a string: ");
        String input = scanner.nextLine();

        // Step 3: Initialize counters for vowels and consonants
        int vowelCount = 0;
        int consonantCount = 0;

        // Step 4: Convert input to lowercase to simplify comparison
        input = input.toLowerCase();

        // Step 5: Loop through each character in the string
        for (int i = 0; i < input.length(); i++) {
            char ch = input.charAt(i);

            // Step 6: Check if the character is a letter
            if ((ch >= 'a' && ch <= 'z')) {
                // Step 7: Check if it's a vowel
                if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
                    vowelCount++;
                } else {
                    consonantCount++;
                }
            }
            // Characters that are not letters are ignored
        }

        // Step 8: Print the result
        System.out.println("Number of vowels: " + vowelCount);
        System.out.println("Number of consonants: " + consonantCount);

        // Step 9: Close the scanner
        scanner.close();
    }
}

🧠 Step-by-Step Explanation


βœ… Step 1 – Taking Input

We use a Scanner to take input from the user.

Scanner scanner = new Scanner(System.in);

βœ… Step 2 – Ask for a String

We prompt the user to enter a line of text.

System.out.print("Enter a string: ");
String input = scanner.nextLine();

βœ… Step 3 – Initialize Counters

We define two variables:

  • vowelCount for vowels

  • consonantCount for consonants

    int vowelCount = 0;
    int consonantCount = 0;
    

    βœ… Step 4 – Convert to Lowercase

    To make checking easier, we convert the input to lowercase.

    input = input.toLowerCase();
    

    This way, we don’t have to check both A and a, or E and e, etc.


    βœ… Step 5 – Loop Through the String

    We loop over every character using a for loop.

     

    for (int i = 0; i < input.length(); i++) {
        char ch = input.charAt(i);
    

    βœ… Step 6 – Check if It's a Letter

    We check if the character is between a to z. This filters out numbers, spaces, and symbols.

    if ((ch >= 'a' && ch <= 'z')) {
    

    βœ… Step 7 – Check for Vowels

    If it’s a vowel (from the list), we increase the vowel counter.

     

    if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
        vowelCount++;
    } else {
        consonantCount++;
    }
    

    If not a vowel, it must be a consonant β€” so we increase consonantCount.


    βœ… Step 8 – Print Results

    After the loop, we display the total count of vowels and consonants.

    System.out.println("Number of vowels: " + vowelCount);
    System.out.println("Number of consonants: " + consonantCount);
    

    βœ… Step 9 – Close the Scanner

    It’s a good practice to close the scanner to prevent resource leaks.

    scanner.close();
    

    πŸ” Example Run

    Enter a string: Hello World
    Number of vowels: 3
    Number of consonants: 7
    

    🎯 Why This Program is Important for Beginners

    • It helps you understand character checking

    • You practice loops and conditionals

    • You get comfortable with user input and string manipulation


    πŸ’‘ Bonus Tip

    If you want to count digits and special characters too, you can add more conditions using:

    Character.isDigit(ch)
    Character.isWhitespace(ch)
    

    🧾 Conclusion

    In this blog post, we learned how to count vowels and consonants in a string using Java. This small but powerful program teaches you key concepts like loops, conditions, and character handling, which are essential for Java programming.

    Keep practicing with variations like counting uppercase vs lowercase letters, spaces, or digits, and you’ll become better at logic building!

     

Comments

TOPICS MENTIONED IN THIS ARTICLE

About the Author(s)

  • Rahul Kumar photo

    Rahul Kumar

    Software Engineer & Tech Editor

    Rahul is a software engineer and editor at Galaxy Founder, passionate about technology, startups, and digital innovation. With a keen eye for emerging trends and a love for clean, efficient code, Rahul shares insights and resources to help others navigate the evolving tech landscape.

    View all articles by Rahul Kumar

Published by Β· Editorial Policy

Galaxy Founder | Latest News, Job Updates & In-Depth Product Reviews β€” Galaxy Founder brings you the latest news, real-time job postings, and honest product reviews to keep you informed, updated, and ahead. Discover trusted content across trending topics only on Galaxy Founder.