Kotlin Program to Check Whether an Alphabet is Vowel or Consonant

In this program, you’ll learn to check whether an alphabet is a vowel or a consotant using if..else and when statement in Kotlin.

Example 1: Check whether an alphabet is vowel or consonant using if..else statement

  1. fun main(args: Array<String>) {
  2. val ch = 'i'
  3. val vowelConsonant = if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') "vowel" else "consonant"
  4. println("$ch is $vowelConsonant")
  5. }

When you run the program, the output will be:

i is vowel

In the above program, 'i' is stored in a char variable ch. In Java, you use double quotes (" ") for strings and single quotes (' ') for characters.

Now, to check whether ch is vowel or not, we check if ch is any of: ('a', 'e', 'i', 'o', 'u'). Unlike Java, this is done using if..else expression as opposed to if..else statement.

If the alphabet is any of the vowels, "vowel" string is returned. Else, "consonant" string is returned.

We can also check for vowel or consonant using a when statement in Kotlin.


Example 2: Check whether an alphabet is vowel or consonant using when statement

  1. fun main(args: Array<String>) {
  2. val ch = 'z'
  3. when(ch) {
  4. 'a', 'e', 'i', 'o', 'u' -> println("$ch is vowel")
  5. else -> println("$ch is consonant")
  6. }
  7. }

When you run the program, the output will be:

z is consonant

In the above program, instead of using a long if condition, we replace it with a when statement. when is similar to switch case in Java.

But, instead of just a statement, when is also an expression, i.e. we can return and store value from when statement.

So, in the program, when ch is either of cases: ('a', 'e', 'i', 'o', 'u'), vowel is printed. Else, else part is executed and consonant is printed on the screen.