Java Program to check the alphabet is vowel or not.
Objective
Write a Java program to check if an entered character is a vowel or a consonant.
Algorithm / Approach
- Prompt the user to input a single character.
- Read the character using
System.in.read(). - Check if the character matches any lowercase vowel: a, e, i, o, u.
- Use an
else ifto check if it matches any uppercase vowel: A, E, I, O, U. - If it doesn't match any of them, it is not a vowel.
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a) throws Exception
{
Scanner s=new Scanner(System.in);
System.out.print("Enter a Character: ");
char x =(char)System.in.read();
if(x=='a' ||x=='e' ||x=='i' ||x=='o' ||x=='u') {
System.out.print("Character is vowel");
}
else if(x=='A' ||x=='E' ||x=='I'||x=='O' ||x=='U') {
System.out.print("Character is vowel");
}
else {
System.out.print("Character is NOT vowel");
}
}
}
Expected Output
Enter a Character: A Character is vowel
Explanation of the Program
- This program uses the logical OR operator
||to check multiple possible equality conditions at once. - If the character matches just one of the conditions (e.g., it is 'e'), the entire condition becomes true.
- It reads a raw byte from the console and casts it to a
char. - Because
System.in.read()can throw an IOException, themainmethod signature includesthrows Exception.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)
Common Mistakes
- Using double quotes
"a"instead of single quotes'a'for characters. - Forgetting to check for uppercase vowels, causing "A" to be incorrectly marked as a consonant.