Introduction:
In this Java program, we will take a character as input from the user and check whether it is a vowel (a, e, i, o, u) or a consonant.
This is a simple program to understand conditional statements and character handling in Java.
๐ป Java Program:
import java.util.Scanner;
public class VowelOrConsonant {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Taking input from user
System.out.print("Enter a character: ");
char ch = sc.next().charAt(0);
// Converting character to lowercase for easy comparison
ch = Character.toLowerCase(ch);
// Checking if the character is a letter
if (ch >= 'a' && ch <= 'z') {
// Checking vowel or consonant
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
System.out.println(ch + " is a Vowel.");
} else {
System.out.println(ch + " is a Consonant.");
}
} else {
System.out.println("Please enter an alphabet character only!");
}
sc.close();
}
}
๐ง Explanation:
-
We use the Scanner class to take input from the user.
-
The entered character is converted to lowercase using
Character.toLowerCase()to handle both uppercase and lowercase letters. -
The program checks:
-
If it’s an alphabet (
atoz). -
If it matches any vowel (
a, e, i, o, u). -
Otherwise, it’s a consonant.
-
๐งพ Example Output:
Enter a character: A
A is a Vowel.
Enter a character: t
t is a Consonant.
Enter a character: 5
Please enter an alphabet character only!
๐ Conclusion:
This program helps beginners understand how to use conditional statements (if-else) and character comparison in Java.
It’s a simple yet effective way to learn about vowels and consonants checking logic.
Comments
Post a Comment