Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program to find whether given character is vowel or consonant using switch case
A switch statement in Java allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case. To verify whether given character is a vowel read a character from the user into a variable (say ch).
Problem Statement
Given a character, write a Java program to determine whether it is a vowel or a consonant using a switch statement.
Input
Enter a character : a
Output
Given character is an vowel
Steps to check whether given character is vowel or consonant
Below are the steps to check whether given character is vowel or consonant ?
- First we will import the Scanner class from java.util package.
- Define a boolean variable bool and initialize it with false.
- Define cases for character ch with vowel characters, both capital and small ('a', 'e', 'i', 'o', 'u' ) without break statements.
- For all these assigns make the bool variable true.
- Finally, if the value of the bool variable is true given character is a vowel else consonant.
Java program to check whether given character is vowel or consonant
A program that demonstrates this is given as follows:
import java.util.Scanner;
public class VowelOrConsonantSwitch {
public static void main(String args[]) {
boolean bool = false;
System.out.println("Enter a character :");
Scanner sc = new Scanner(System.in);
char ch = sc.next().charAt(0);
switch(ch) {
case 'A' :
case 'E' :
case 'I' :
case 'O' :
case 'U' :
case 'a' :
case 'e' :
case 'i' :
case 'o' :
case 'u' :
bool = true;
}
if(bool == true) {
System.out.println("Given character is an vowel ");
} else {
System.out.println("Given character is a consonant ");
}
}
}
Output
Enter a character : a Given character is an vowel Enter a character : l Given character is a consonant
Code Explanation
This Java program starts by importing java.util.Scanner to read user input and initializes a boolean variable bool to false. The user is prompted to enter a character, stored in the variable ch. A switch statement then checks ch against all vowel characters (both uppercase and lowercase). If ch matches a vowel, bool is set to true. Finally, the program checks bool and prints "Given character is a vowel" if true, or "Given character is a consonant" if false.