Java Program to Count Vowels and Consonants in a String (Java 8)

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

Introduction

Counting the number of vowels and consonants in a string is a common task in text processing. This guide will show you how to perform this task using both traditional Java methods and Java 8's Stream API.

Problem Statement

Create Java programs that take a string input and count the number of vowels and consonants in the string using both traditional and Java 8 methods.

Example 1:

  • Input: "Hello World"
  • Output: Vowels: 3, Consonants: 7

Example 2:

  • Input: "Java Programming"
  • Output: Vowels: 5, Consonants: 9

Approach 1: Using Traditional Methods (Without Java 8)

Solution Steps

  1. Input String: Accept a string input from the user.
  2. Normalize the String: Convert the string to lowercase to make the comparison case-insensitive.
  3. Iterate Over the Characters: Loop through each character of the string.
  4. Count Vowels and Consonants: Use if-else conditions to check whether each character is a vowel or consonant and increment the respective counters.
  5. Output the Result: Display the counts of vowels and consonants.

Java Program

import java.util.Scanner; /** * Java Program to Count Vowels and Consonants in a String (Without Java 8) * Author: https://www.javaguides.net/ */ public class VowelConsonantCounterTraditional { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Step 1: Input String System.out.print("Enter a string: "); String input = scanner.nextLine(); // Step 2: Normalize the String input = input.toLowerCase(); // Step 3: Initialize vowel and consonant counters int vowelCount = 0; int consonantCount = 0; // Step 4: Iterate over each character in the string for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); // Step 5: Check if the character is a vowel if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { vowelCount++; } // Step 6: Check if the character is a consonant else if (c >= 'a' && c <= 'z') { consonantCount++; } } // Step 7: Output the Result System.out.println("Vowels: " + vowelCount + ", Consonants: " + consonantCount); } } 

Output Example

For the input "Hello World", the output will be:

Enter a string: Hello World Vowels: 3, Consonants: 7 

Explanation

  • Input: The program prompts the user to enter a string.
  • Normalization: The string is converted to lowercase to ensure consistent comparisons.
  • Iteration: The program loops through each character in the string.
  • Vowel and Consonant Counting: The program checks if each character is a vowel or consonant using conditional statements and increments the corresponding counter.
  • Output: The program displays the counts of vowels and consonants.

Approach 2: Using Java 8 Stream API

Solution Steps

  1. Input String: Accept a string input from the user.
  2. Normalize the String: Convert the string to lowercase to make the comparison case-insensitive.
  3. Filter and Count Vowels: Use a stream to filter the characters that are vowels and count them.
  4. Filter and Count Consonants: Use a stream to filter the characters that are consonants and count them.
  5. Output the Result: Display the counts of vowels and consonants.

Java Program

import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.util.function.Predicate; /** * Java Program to Count Vowels and Consonants in a String using Java 8 * Author: https://www.javaguides.net/ */ public class VowelConsonantCounterJava8 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Step 1: Input String System.out.print("Enter a string: "); String input = scanner.nextLine(); // Step 2: Normalize the String input = input.toLowerCase(); // Step 3: Define the sets of vowels List<Character> vowels = Arrays.asList('a', 'e', 'i', 'o', 'u'); // Step 4: Filter and Count Vowels long vowelCount = input.chars() .mapToObj(c -> (char) c) .filter(vowels::contains) .count(); // Step 5: Filter and Count Consonants Predicate<Character> isAlphabet = c -> c >= 'a' && c <= 'z'; long consonantCount = input.chars() .mapToObj(c -> (char) c) .filter(isAlphabet.and(c -> !vowels.contains(c))) .count(); // Step 6: Output the Result System.out.println("Vowels: " + vowelCount + ", Consonants: " + consonantCount); } } 

Output Example

For the input "Hello World", the output will be:

Enter a string: Hello World Vowels: 3, Consonants: 7 

Explanation

  • Input: The program prompts the user to enter a string.
  • Normalization: The string is converted to lowercase to ensure consistent comparisons.
  • Vowel and Consonant Counting: The program uses streams to filter and count vowels and consonants efficiently.
  • Output: The program displays the counts of vowels and consonants.

Conclusion

This guide demonstrated how to count vowels and consonants in a string using both traditional methods and the Java 8 Stream API. The traditional approach uses a loop and conditional statements, while the Java 8 approach leverages streams to perform the task in a more functional and concise manner. Both methods are effective, and the choice between them depends on your preference and the context in which you're working.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare