Kotlin - if-else Statement Example

The if-else statement also tests the condition. It executes the if block if a condition is true otherwise else block, is executed.

Syntax:

if(condition){  statement 1; //code if condition is true  }else{  statement 2; //code if condition is false  } 
Here, each statement may be a single statement or a compound statement enclosed in curly braces (that is, a block). The condition is an expression that returns a boolean value.
The if works like this: If the condition is true, then statement1 is executed. Otherwise, statement2 (if it exists) is executed.

Kotlin - if-else Statement Example

package net.javaguides.kotlin fun main(args: Array < String > ) { var testscore = 76; var grade = ' '; if (testscore >= 90) { grade = 'A'; } else if (testscore >= 80) { grade = 'B' } else if (testscore >= 70) { grade = 'C'; } else if (testscore >= 60) { grade = 'D'; } else { grade = 'F'; } System.out.println("Grade = " + grade); }
Output:
Grade = C


Comments