Kotlin Training Program

DOWNLOAD APP

FEEDBACK

if-else statement

if statement is used to execute a block of code only when a certain condition is met. For example, following code prints "You can vote!" only when age >= 18 otherwise nothing is printed :

 fun main() {
		print("Enter your age: ")
		val age = readLine()!!.toInt()
		if (age >= 18)
		    print("You can vote!")
}
 

if statement can optionally be accompanied by else statement. In above example, if we want to print "You can not vote!" when age < 18, we can add an else statement :

 fun main() {
		print("Enter your age: ")
		val age = readLine()!!.toInt()
		if (age >= 18)
		    print("You can vote!")
		else
		    print("You can not vote!")
}
 

If we want to execute multiple lines of code under if or else, we can wrap the code inside a code block using curly braces {} :

 if (/* Condition */) {
    // Code
} else {
    // Code
}