How to Check Vowel or Consonant using Switch Case in Java Program ?

  Java Interview Q&A

Dear reader, today we will read in Java program whether the character is a vowel or a consonant. The letters A, E, I, O and U (smallcase and uppercase) are known as vowels and the rest of the letters are known as consonants. Here we will write a Java program that checks whether the input character is a vowel or a consonant using a switch case in Java.

To check vowels or consonants using a Java program switch case

In this program we are not intentionally using the break statement with cases, so that if the user enters any vowel, the program continues to execute all subsequent cases until case ‘u’ Does not arrive and where we are setting the value of a stupid variable to true. In this way we can identify whether the alphabet is the vowel entered by the user.

import java.util.Scanner;
class JavaExample
{
   public static void main(String[ ] arg)
   {
	boolean isVowel=false;;
	Scanner scanner=new Scanner(System.in);
	System.out.println("Enter a character : ");
	char ch=scanner.next().charAt(0); 
	scanner.close();
	switch(ch)
	{
	   case 'a' :
	   case 'e' :
    	   case 'i' :
	   case 'o' :
	   case 'u' :
	   case 'A' :
	   case 'E' :
	   case 'I' :
	   case 'O' :
	   case 'U' : isVowel = true;
	}
	if(isVowel == true) {
	   System.out.println(ch+" is  a Vowel");
	}
	else {
	   if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
		System.out.println(ch+" is a Consonant");
	   else
		System.out.println("Input is not an alphabet");		
        }
   }
}

Output 1:

Enter a character : 
A
A is  a Vowel

Output 2:

Enter a character : 
P
P is a Consonant

Output 3:

Enter a character : 
9
Input is not an alphabet

Read here. JAVA Tutorial

LEAVE A COMMENT