In this tutorial, we are going to learn writing java program to check if the character is a vowel ( a, e, i, o, u) or any other alphabet other than vowels i.e. consonants.
For any input character, we have to check whether a character is a vowel or consonant.
For example
Case 1: If a user is given input a or A
The output should be “Vowel”
As we know that A is a vowel
Case2: If the user is given b or B
The output should be “consonant”
As we know that B is consonant
Check Given Character is Vowel or Consonant in Java
import java.util.*;
public class Main {
public static void main (String[]args) {
System.out.println("Java program to check given character is vowel or consonant");
Scanner sc = new Scanner (System.in);
System.out.println ("Please enter a character");
char ch = sc.next ().charAt (0);
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
if (ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i'
|| ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
System.out.println ("Given Character " + ch + " is a vowel.\n");
else
System.out.println ("Given Character " + ch + " is a consonant.\n");
}
else
System.out.println ("Given Character " + ch +" is neither a vowel nor a consonant.\n");
}
}
Output 1:
Java program to check given character is vowel or consonant
Please enter a character
E
Given Character E is a vowel.
Explanation
As we can see for the character ‘E’ output generated is “Vowel”, which is obvious as ‘E’ is a vowel and satisfying the ‘if ’ statement
Output 2:
Java program to check given character is vowel or consonant
Please enter a character
S
Given Character S is a consonant.
Explanation
Similarly, for the character ‘s’ output generated is “consonant”, as s is not a vowel and does not satisfy the ‘if ’ statement