If - Else
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 30 of 93.
A basic if statement only runs code when the condition is true. But what if you want to do something different when the condition is false? That's where else comes in.
The else block provides an alternative path: code that runs only when the if condition evaluates to false:
fun main() {
val age = 15
if (age >= 18) {
println("You can vote!")
} else {
println("You're too young to vote.")
}
}In this example, since age is 15, the condition age >= 18 is false, so Kotlin skips the first block and executes the else block instead, printing "You're too young to vote."
You can also chain multiple conditions using else if to check several possibilities in sequence:
fun main() {
val score = 75
if (score >= 90) {
println("Grade: A")
} else if (score >= 80) {
println("Grade: B")
} else if (score >= 70) {
println("Grade: C")
} else {
println("Grade: F")
}
}Kotlin evaluates each condition from top to bottom and executes only the first block whose condition is true. Once a match is found, the remaining conditions are skipped entirely.
Challenge
EasyYou are provided with the following variable:
val temperature = -5Use if, else if, and else to print a message based on the temperature value:
- If the temperature is greater than 30, print
Hot - If the temperature is greater than 20, print
Warm - If the temperature is greater than 10, print
Cool - If the temperature is greater than 0, print
Cold - Otherwise, print
Freezing
Try it yourself
fun main() {
val temperature = -5
// TODO: Write your code below
// Use if, else if, and else to print the appropriate message based on temperature
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground