Java Interview Questions ยท Coding Problems
Learn how to iterate through a string and use conditional logic to check for the presence of vowels.
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.");
}
}
}main method.str is declared and initialized with the value "Hello World". This value is stored in the String Pool.vowelPresent is initialized to false. We will use this to track if we find a vowel.for loop is initiated. The loop control variable i is declared and initialized to 0.i < str.length() (0 < 11). The condition is true, so the loop body will execute.i (0) of the string str is retrieved. The character is 'H', which is assigned to the variable ch.if condition checks if ch ('H') is a vowel. The condition is false.i is incremented. i is now 1.i < str.length() (1 < 11). The condition is true.i (1) is retrieved. The character is 'e', which is assigned to ch.if condition checks if ch ('e') is a vowel. The condition ch == 'e' is true, so the entire if condition becomes true.if block. The vowelPresent flag is set to true.break statement is executed. This immediately terminates the for loop.if (vowelPresent) is checked. Since vowelPresent is true, the condition is met.main method has finished executing, and the program terminates.