Conditional Statements
# CHAPTER 7
Conditional Statements
1. Chapter Introduction
Until now, our programs have executed sequentially, line by line. To build intelligent applications, our code needs to make decisions based on changing data. In this chapter, we will learn about Control Flow. We will explore standardif-else statements, learn how Kotlin treats if as an *expression* (meaning it can return a value!), and discover the incredibly powerful when construct, which replaces the clunky switch statement found in other languages.
2. Learning Objectives
By the end of this chapter, you will be able to:-
Use standard
if,else if, andelsestatements.
-
Assign values dynamically using
ifas an Expression.
-
Use the
whenstatement for multi-branch logic.
-
Replace Java's
switchstatement withwhen.
- Build a Mini Project: Grade Calculator.
3. The if Statement
The if statement executes a block of code only if a specific condition evaluates to true.
For multiple conditions, use else if:
4. if as an Expression (Kotlin Superpower)
In Java, if is a *statement* (it just performs an action). In Kotlin, if is an Expression—meaning it evaluates to a value that you can assign directly to a variable!
Because of this, Kotlin does not have a Ternary Operator (condition ? true : false). It doesn't need one!
*Note: If you use if as an expression, it MUST have an else branch.*
5. The when Expression
If you have a long chain of else if statements, the code gets very messy. Other languages use switch, but Kotlin uses the when expression, which is significantly more powerful.
#### Advanced when Usage
when can check multiple conditions, ranges, and even types!
6. Mini Project: Grade Calculator
Let's build a dynamic grade calculator that asks for a score and uses awhen expression to assign a letter grade.
7. Common Mistakes
-
Forgetting
elsein Expressions: If you assign the result of aniforwhento a variable, you MUST provide anelsebranch. The compiler needs a guarantee that the variable will definitely receive *some* value.
-
Using Java's
switch: Kotlin does not have theswitchkeyword. Attempting to use it will result in a syntax error.
8. Best Practices
-
Prefer
whenoverelse if: If you have more than two branches of logic checking the same variable, always usewhen. It is vastly more readable.
-
Single-line logic: Use the inline
ifexpression (val res = if (x) a else b) instead of creating a mutablevarand assigning it inside standardif/elseblocks.
9. Exercises
-
1.
Write a program that asks for the user's current
temperature.
-
2.
Use an
ifexpression to assign aStringvariableclothing.
-
3.
If temp > 25,
clothing= "T-Shirt". Else,clothing= "Jacket".
- 4. Print the result.
10. MCQs with Answers
What keyword is used to execute code only if a condition is true?
In Kotlin, if can be used as an Expression. What does this mean?
condition ? a : b)?
a) Yes b) No, because if/else can be used as an expression on a single line
Answer: b) No.
If you use if as an expression to assign a variable, what is strictly required?
What construct in Kotlin replaces the Java switch statement?
What keyword acts as the "default" case inside a when block?
when expression check if a number is inside a range?
a) Yes, using the in keyword (e.g., in 1..10) b) No
Answer: a) Yes.
Q8. Can a single branch in a when expression match multiple values?
a) Yes, by separating them with commas (e.g., 1, 2, 3 ->) b) No
Answer: a) Yes.
Q9. Like if, can when be used as an expression to assign a variable?
a) Yes b) No
Answer: a) Yes.
If checking multiple ranges inside when(score), which branch executes?
11. Interview Questions
-
Q: Explain how Kotlin's
ifexpression eliminates the need for a ternary operator. Provide a code example.
-
Q: Compare Java's
switchstatement with Kotlin'swhenexpression. Why iswhenconsidered superior? (Answer:whendoesn't requirebreakstatements, prevents fall-through bugs, can be used as an expression, and supports complex range/type checking).
12. Summary
Control flow is what makes an application "smart." By turningif and when into Expressions that return values, Kotlin drastically reduces the need for mutable var variables, leading to cleaner and safer code. The when expression is one of Kotlin's most beloved features, making complex multi-branch logic a joy to read.
13. Next Chapter Recommendation
Our code can make decisions, but it still only runs once. What if we want to do something 100 times? In Chapter 8: Loops in Kotlin, we will explore how to repeat tasks efficiently usingfor and while loops, and dive deeper into Kotlin Ranges.