Java Interview Questions ยท Coding Problems

Checking for Vowels in a String

Learn how to iterate through a string and use conditional logic to check for the presence of vowels.

VowelChecker.java

public class VowelChecker {
    public static void main(String[] args) {
        String str = "Hello World";
        boolean vowelPresent = false;

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
                ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
                vowelPresent = true;
                break;
            }
        }

        if (vowelPresent) {
            System.out.println("Vowel is present in the string.");
        } else {
            System.out.println("Vowel is not present in the string.");
        }
    }
}

Step by step

  1. The program execution starts inside the main method.
  2. A string variable str is declared and initialized with the value "Hello World". This value is stored in the String Pool.
  3. A boolean flag vowelPresent is initialized to false. We will use this to track if we find a vowel.
  4. The for loop is initiated. The loop control variable i is declared and initialized to 0.
  5. The loop condition is checked: i < str.length() (0 < 11). The condition is true, so the loop body will execute.
  6. The character at index i (0) of the string str is retrieved. The character is 'H', which is assigned to the variable ch.
  7. The if condition checks if ch ('H') is a vowel. The condition is false.
  8. The loop variable i is incremented. i is now 1.
  9. The loop condition is checked again: i < str.length() (1 < 11). The condition is true.
  10. The character at index i (1) is retrieved. The character is 'e', which is assigned to ch.
  11. The if condition checks if ch ('e') is a vowel. The condition ch == 'e' is true, so the entire if condition becomes true.
  12. Since the condition is true, we enter the if block. The vowelPresent flag is set to true.
  13. The break statement is executed. This immediately terminates the for loop.
  14. Execution continues after the loop. The condition if (vowelPresent) is checked. Since vowelPresent is true, the condition is met.
  15. The message "Vowel is present in the string." is printed to the console.
  16. The main method has finished executing, and the program terminates.