In this article, we will learn how to write a Java program to identify all strings in an array that start with a vowel. This is a simple yet practical exercise for working with arrays and understanding string properties in Java.
Problem statement:
We are given an array of strings, and the task is to identify all strings that start with a vowel (a, e, i, o, u).
Approach to Solve the Problem
- Check for Vowels:
- For each string in the array, check if the first character is a vowel.
- Handle Case Sensitivity:
- Consider both uppercase and lowercase vowels.
- Store Results:
- Add strings that start with a vowel to a list.
- Display Results:
- Print the list of strings starting with a vowel.
Java program to Find Strings starting with a Vowel in Array
Here is the Java program to solve the problem:
package com.javacodepoint.stringarray;
import java.util.ArrayList;
import java.util.List;
public class StringsStartingWithVowel {
public static void main(String[] args) {
// Input array of strings
String[] words = { "apple", "banana", "orange", "umbrella", "grape" };
// Call the method to find strings starting with a vowel
List<String> vowelStartStrings = findStringsStartingWithVowel(words);
// Display the results
System.out.println("Strings starting with a vowel: " + String.join(", ", vowelStartStrings));
}
// Method to find strings starting with a vowel
public static List<String> findStringsStartingWithVowel(String[] words) {
List<String> result = new ArrayList<>();
String vowels = "aeiouAEIOU";
// Check each string in the array
for (String word : words) {
if (!word.isEmpty() && vowels.indexOf(word.charAt(0)) != -1) {
result.add(word);
}
}
return result;
}
}
OUTPUT:
Strings starting with a vowel: apple, orange, umbrella
Code Explanation:
- Input Array: The array
words
contains the strings to be checked. - Check First Character:
- Use
word.charAt(0)
to check the first character of each string. - Compare it against the string
vowels
to see if it matches any vowel.
- Use
- Add to Results:
- If the string starts with a vowel, add it to the list
result
.
- If the string starts with a vowel, add it to the list
- Output Results:
- The program prints all strings starting with a vowel.
Conclusion
This program provides a simple and effective way to find strings that start with a vowel in an array. This program helps solidify important programming skills, including handling strings, navigating arrays, and implementing conditional logic in Java. Practicing this program will help you improve your problem-solving skills in Java.
You can learn the Top 20 string array programs for interview preparation (Click here).