In Java, determining whether a given character is a vowel or a consonant is a common programming task that helps beginners understand control flow statements like if-else and switch-case. In this article, we will explore how to implement this functionality with code examples and explanations.

What is a Vowel and a Consonant?

Using If-Else Statement in Java

Here’s a simple program that checks if an input character is a vowel or consonant using the if-else statement.

Code Example

import java.util.Scanner;

public class VowelConsonantChecker {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a single alphabet: ");
        char ch = scanner.next().toLowerCase().charAt(0); // Read input and convert to lowercase

        if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
            System.out.println(ch + " is a vowel.");
        } else if (ch >= 'a' && ch <= 'z') {
            System.out.println(ch + " is a consonant.");
        } else {
            System.out.println("Input is not a valid alphabet.");
        }

        scanner.close();
    }
}

Explanation

Output

Vowel and consonant in Java

Using Switch Statement in Java

You can also achieve the same functionality using a switch statement, which can make the code more readable when checking multiple conditions.

Code Example

import java.util.Scanner;

public class VowelConsonantChecker {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a single alphabet: ");
        char ch = scanner.next().toLowerCase().charAt(0); // Read input and convert to lowercase

        switch (ch) {
            case 'a':
            case 'e':
            case 'i':
            case 'o':
            case 'u':
                System.out.println(ch + " is a vowel.");
                break;
            default:
                if (ch >= 'a' && ch <= 'z') {
                    System.out.println(ch + " is a consonant.");
                } else {
                    System.out.println("Input is not a valid alphabet.");
                }
                break;
        }

        scanner.close();
    }
}

Explanation

Output

Vowel and consonant checker in Java

Conclusion

In this article, we explored how to check whether an input character is a vowel or consonant in Java. We demonstrated two methods using if-else statements and switch statements. Understanding these concepts will help you build foundational skills in handling conditional logic in programming. You can further enhance these examples by adding features such as handling numeric inputs or special characters for more robust applications.