Kotlin If Else Statements
This if-else is a keyword that are used to define conditional statement. This statement is based on an expression or boolean values. expression result is always should be in form of boolean value. This boolean value is true then executes if-block statement. Otherwise check other else-if statements or executes else-block statement. This else statement is optionally, when if-block condition are not satisfied.
if(expression){
//true expression
}else{
//false expression
}
For example
fun main(args: Array<String>) {
var number:Int =5
if(number==5){
print("number is Five")
}else{
print("number is not Five")
}
}
Output
number is Five
We can also make ternary operators using of if-else statements.
fun main(args: Array<String>) {
val num1:Int =10
val num2:Int =20
//implement ternary operator
val big:Int =if(num1>num2) num1 else num2
println("$big")
}
Output
20
Kotlin if.. else if.. else
when checking multiple condition into single or multiple variable then we can use if and else-if statement.
if(expresion1){
//logical code
}else if(expression2){
//logical code
//group of statements
}else if(expression3){
//logical code
//group of statements
}else{
//else portion
}
for example.
fun main(args: Array<String>) {
var grade:Char='A'
if(grade=='A'){
//when grade value is equal to A
println("Pass, with excellent marks")
}else if(grade=='B'){
println("Pass, with Good marks")
}
else if(grade=='C'){
println("Pass, with Average marks")
}else{
//executes this block when not
//satisfied above all condition
println("Result is Pending")
}
}
Output
Pass, with excellent marks
Kotlin Nested If else Statement
Defining of one statement inside other statement that is called nested statement. some of situation we can need to define the nested statement in our program.
if(expression){
//statements
if(inner-expression2){
//statements
if(sub-expression1){
//statements
}else if(sub-expression2){
//statements
}
}
if(inner-expression2){
//statements
}
}
For example.
fun main(args: Array<String>) {
var num:Int=100
if(num<1000){
//nested statement
if(num<500){
println("Num is less than to 500")
}else{
println("Num is greater than or equal to 500")
}
}else{
println("Num is greater than or equal to 1000")
}
}
Output
Num is less than to 500
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment