Check If a Letter is A Vowel or A Consonant in Java

Exercise:

Write a java program to check whether a letter is a vowel or a consonant.

1.Check using if..else statement

Click Here to View the Solution!
public class VowelConsonantChecker {
 
    public static void main(String[] args) {
 
        char alphabet = 'm';
 
if(alphabet=='a' || alphabet=='e' || alphabet=='i' || alphabet=='o' || alphabet=='u' )
            System.out.println(alphabet+ " is vowel");
        else
            System.out.println(alphabet+ " is consonant");
 
    }
} 
Click Here to View the Output!
m is consonant
Click Here to View the Explanation!
  • This program is dealing with character variables and identifying that whether the entered character (alphabet) is a vowel or a consonant using the if…else statement. It then displays the result.
  • By default, the character variable alphabet will hold ‘m’. Java distinguishes the character values and string values through single and double quotes.
  • The program states all the vowel characters in the if statement (‘a’,’e’,’i’,’o’,’u’). So, whenever the entered value is to be checked that whether it is a vowel or a consonant, the program will match the entered character alphabet with all the characters listed in the if statement.
  • If the alphabet matches any character in the if statement, it will be a vowel else it will be a consonant.
  • This identification process can also be done through the Switch statement which is another function of Java.

2.Check using switch statement

Click Here to View the Solution!
public class VowelConsonantChecker {
 
    public static void main(String[] args) {
 
        char alphabet = 'e';
 
        switch (alphabet) {
            case 'a':
            case 'e':
            case 'i':
            case 'o':
            case 'u':
                System.out.println(alphabet + " is a vowel.");
                break;
            default:
                System.out.println(alphabet + " is a consonant.");
        }
    }
} 
Click Here to View the Output!
e is a vowel.
Click Here to View the Explanation!
  • This program like the above one, checks whether the entered alphabet is a vowel or a consonant. But instead of using the if…else statement, it uses the switch case statement.
  • The vowel characters are stated in each case (‘a’, ‘e’, ‘i’, ‘o’, ‘u’), and if the entered character alphabet matches any of the case, the term “vowel” is printed. And if the alphabet matches no case, the term “consonant” is printed.
%d bloggers like this: