English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Complete Collection of Kotlin Examples
In this program, you will learn to use the if..else and when statements in Kotlin to check if a letter is a vowel or consonant.
fun main(args: Array<String>) { val ch = 'i' val vowelConsonant = if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') "vowel letter" else "consonant letter" println("$ch is $vowelConsonant") }
When running the program, the output is:
i is a vowel letter
In the above program, 'i' is stored in the char variable ch. In Java, double quotes (" ") are used for strings, and single quotes (' ') for characters.
Now, to check if ch is a vowel, we check if ch is any of the following: ('a', 'e', 'i', 'o', 'u'). Unlike Java, this is done using an if..else expression rather than an if..else statement.
If the letter is any vowel, return the string "vowel letter". Otherwise, return the string "consonant letter".
We can also use the when statement in Kotlin to check if a letter is a vowel or consonant.
fun main(args: Array<String>) { val ch = 'z' when(ch) { 'a', 'e', 'i', 'o', 'u' -> println("$ch is a vowel letter") else -> println("$ch is a consonant letter") } }
When running the program, the output is:
z is a consonant letter
In the above program, we did not use a long if condition, but replaced it with a when statement. When is similar to the switch case in Java.
But, when is not just a statement, it is also an expression, which means we can return and store values from the when statement.
Therefore, in the program, when ch is any of the following: ('a', 'e', 'i', 'o', 'u'), it will output a vowel. Otherwise, the else part will execute and the consonant will be printed on the screen.
This is equivalent Java code: Check Java inis a Vowel or Consonant