If Statement
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 29 of 93.
You've learned how to create Boolean expressions using comparison and logical operators. Now it's time to use those expressions to control what your program actually does. The if statement lets you execute code only when a condition is true.
The basic structure places a condition inside parentheses, followed by curly braces containing the code to run:
fun main() {
val temperature = 35
if (temperature > 30) {
println("It's hot outside!")
}
}When Kotlin reaches the if statement, it evaluates the condition. If temperature > 30 is true, the code inside the braces executes. If it's false, Kotlin skips that block entirely and continues with the rest of the program.
You can include multiple statements inside the braces, and you can use any Boolean expression as the condition, including those with logical operators:
fun main() {
val age = 25
val hasTicket = true
if (age >= 18 && hasTicket) {
println("Welcome to the concert!")
println("Enjoy the show!")
}
}Both conditions must be true for the messages to print. This is how programs make decisions: executing different code paths based on the current state of your data.
Challenge
EasyWrite a function checkSpeed that takes speed and returns a warning message if the speed exceeds the limit.
Use an if statement to check if the speed is greater than 60. If it is, return "Warning: Too fast!". Otherwise, return "Speed OK".
Parameters:
speed(Int): The current speed
Returns: "Warning: Too fast!" if speed is greater than 60, "Speed OK" otherwise (String)
Try it yourself
fun checkSpeed(speed: Int): String {
// Write code here
}
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