Write a Java Program to Check Whether an Alphabet is Vowel or Consonant

In Java, we can check whether a given alphabet is a vowel or consonant by using if-else statements.

Here’s a program that takes an alphabet as input from the user and checks whether it’s a vowel or a consonant.

import java.util.Scanner;

public class VowelOrConsonant {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter an alphabet: ");
        char ch = scanner.next().charAt(0);

        if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
                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");

Let’s go through the code step by step.

First, we import the Scanner class from the java.util package.

This allows us to take user input from the command line.

Next, we create a class called VowelOrConsonant.

Inside this class, we define a main method that takes no arguments.

Inside the main method, we create a Scanner object called scanner.

We use this object to take user input from the command line.

We prompt the user to enter an alphabet by printing the message “Enter an alphabet: ” to the console.

We then use the next() method of the Scanner class to take a String input from the user.

We immediately call the charAt(0) method on the String to extract the first character of the input, which should be an alphabet.

We store this character in a variable called ch.

We then use an if-else statement to check whether ch is a vowel or a consonant.

We use logical OR operators to check if ch is equal to any of the vowel characters (a, e, i, o, u) in both upper and lower case.

If ch is a vowel, we print the message “ch is a vowel” to the console.

Otherwise, we print the message “ch is a consonant” to the console.

That’s it! This program should correctly identify whether a given alphabet is a vowel or a consonant.

Editorial Team
Editorial Team

Programming Cube website is a resource for you to find the best tutorials and articles on programming and coding.