The if expression

The if expression is used to make a logical decision based on the fulfillment of a condition. We make use of the if keyword to write if expressions:

val a = 1

if (a == 1) {
print("a is one")
}

The preceding if expression tests whether the a == 1 (read: a is equal to 1) condition holds true. If the condition is true, the a is one string is printed on the screen, otherwise nothing is printed.

An if expressions often has one or more accompanying else or else if keywords. These accompanying keywords can be used to further control the flow of a program. Take the following if expression for example:

val a = 4
if (a == 1) {
print("a is equal to one.")
} else if (a == 2) {
print("a is equal to two.")
} else {
print("a is neither one nor two.")
}

The preceding expression first tests whether a is equal to 1. This test evaluates to false so, the following condition has been tested. Surely a is not equal to 2. Hence the second condition evaluates to false. As a result of all previous conditions evaluating to false, the final statement is executed. Hence a is neither one nor two. is printed on the screen.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.144.108