C Programs Tutorials | IT Developer
IT Developer

Java Programs



Share with a Friend

Introduction to Java

Check if a Character is Vowel or Consonant - Java Program

import java.util.Scanner;

 

public class VowelConsonantCheck {

    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); // Read single character

 

        // Convert to lowercase to simplify comparison

        ch = Character.toLowerCase(ch);

 

        // Check if alphabet

        if (ch < 'a' || ch > 'z') {

            System.out.println("Invalid input! Please enter an alphabet.");

        }

        else 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.");

        }

 

        sc.close();

    }

}

Output

 
OUTPUT 1:
Enter a character: A
a is a Vowel.

OUTPUT 2:
Enter a character: k
k is a Consonant.

OUTPUT 3: 
Enter a character: 9
Invalid input! Please enter an alphabet.

Explanation

Step 1: Input

The user enters a single character:

char ch = sc.next().charAt(0);

This reads the first character of the user input.

Step 2: Convert to lowercase

This ensures that both uppercase and lowercase characters are handled:

ch = Character.toLowerCase(ch);

Step 3: Check if it is an alphabet

Characters outside 'a' to 'z' are invalid.

if (ch < 'a' || ch > 'z')

Step 4: Check for vowel

We compare against the 5 vowels:

ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u'

Step 5: Otherwise it is a consonant