TechByteByByte

Check if a Vowel is Present in a String - Java

An easy QA/automation coding interview question: check if a Vowel is Present in a String, with a full Java walkthrough, dry run, and common interviewer follow-ups.

#Strings#Loops#Character Methods#Easy#Java

Category: Easy | Concepts used: String iteration, character checks, character sets


Problem Statement

Given a string, check whether it contains at least one vowel (a, e, i, o, u โ€” uppercase or lowercase).

Input : "Hello"      Input : "sky"       Input : "PQRST"
Output: true          Output: false        Output: false

Examples (with edge scenarios)

#InputOutputWhy
1"Hello"trueContains e, o
2"sky"falsey is not treated as a vowel
3"" (empty string)falseContains no characters
4"AEIOU"trueCase-insensitive match
5"123 xyz!"falseOnly contains digits, spaces, symbols, and consonants

โš ๏ธ Common Beginner Mistake

MistakeImpactFix
Checking only lowercase vowelsMisses uppercase inputs like "HELLO"Convert the character or string to lowercase before checking
Forgetting the empty string caseThrows out-of-bounds error on custom indexingEnsure the loop range is correctly set to < length() and the default return is false

Before You Code: Clarify the Contract

Before choosing an algorithm, confirm how null and empty strings should behave, whether comparison is case-sensitive, and whether spaces or punctuation count. Java char values are UTF-16 code units, not always complete human-visible Unicode characters, so international text may require code points or grapheme-aware libraries.

Analogy: Sorting Mail at a Post Office

Imagine you are a postal worker checking a box of incoming letters:

  • You have a strict rule: โ€œIf there is even one letter in this box addressed to the VIP suite (Vowels), flag the whole box immediately.โ€
  • You pull the letters out one by one. The moment you see a letter addressed to A, E, I, O, or U, you stop digging, raise the flag (return true), and move on.
  • If you check the entire box and never see a VIP address, you put the box down without a flag (return false).

Solution 1 โ€” Loop + if-else Chain (Most Basic)

This is the standard iterative approach checking every character sequentially.

Intuition

To find if a string contains a vowel, we inspect each character one by one. Returning true as soon as a vowel is found (early exit / short-circuiting) saves unnecessary CPU cycles.

public class VowelCheck {
    public static boolean hasVowel(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }

// Convert to lowercase once to handle case-insensitivity
        String lower = str.toLowerCase();

for (int i = 0; i < lower.length(); i++) {
            char ch = lower.charAt(i);
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
                return true; // Found one vowel, stop immediately
            }
        }
        return false; // Loop finished without finding any vowel
    }

public static void main(String[] args) {
        System.out.println(hasVowel("Hello"));   // true
        System.out.println(hasVowel("sky"));     // false
        System.out.println(hasVowel(""));        // false
        System.out.println(hasVowel("AEIOU"));   // true
    }
}

Output:

true
false
false
true

Dry Run (str = โ€œskyโ€)

lower = "sky"
i = 0: ch = 's' -> not a vowel
i = 1: ch = 'k' -> not a vowel
i = 2: ch = 'y' -> not a vowel
Loop ends -> return false

Solution 2 โ€” Lookup Set via String.contains() (Concise)

Using a constant string reference containing all vowels simplifies syntax.

Intuition

Instead of chaining || operators, we define a reference string of vowels ("aeiouAEIOU") and verify whether each character of the input exists inside it using String.indexOf() or String.contains().

public class VowelCheckContains {
    public static boolean hasVowel(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }

String vowels = "aeiouAEIOU";
        for (char ch : str.toCharArray()) {
            // String.indexOf(ch) >= 0 is more efficient than string conversion for contains()
            if (vowels.indexOf(ch) != -1) {
                return true;
            }
        }
        return false;
    }

public static void main(String[] args) {
        System.out.println(hasVowel("Hello"));  // true
        System.out.println(hasVowel("sky"));    // false
    }
}

Output:

true
false

๐Ÿ“Š Visual Flowchart

graph TD
    Start["Input String S"] --> Empty{"S is empty/null?"}
    Empty -->|Yes| RetFalse["Return False"]
    Empty -->|No| Iterate["Iterate through chars"]
    Iterate --> Loop{"More characters?"}
    Loop -->|Yes| Inspect{"Is char in 'aeiouAEIOU'?"}
    Inspect -->|Yes| Found["Return True"]
    Inspect -->|No| Loop
    Loop -->|No| NotFound["Return False"]

Interviewer Insights

This question is a filter for basic logical flow control and edge case analysis.

Follow-up questions you might get:

  • โ€œHow can you solve this using Regular Expressions?โ€ โ†’ Mention str.matches(".*[aeiouAEIOU].*"). While regex is concise, regular loops are generally faster because compiling and matching regex objects carries computational overhead.
  • โ€œWhat is the time complexity if the string is very long?โ€ โ†’ It is (O(N)) where (N) is the length of the string, since in the worst-case scenario (no vowels), we must inspect every character exactly once.

Quick Recap

ApproachTime ComplexitySpace ComplexityHandles Negatives/Symbols?Interview Signal
Loop + if-else(O(N))(O(1))YesSimple, robust, clear logical boundaries
Lookup String(O(N))(O(1))YesClean lookup representation, avoids complex `
Author
TechByteByByte Editorial Team
Reviewed by
TechByteByByte Admin
Published
Last reviewed