Combining Multiple Conditions
Swipe to show menu
Combining Logical Conditions
When you need to check if more than one condition is true or false, use logical operators to combine them. In Kotlin, the main operators for this are AND (&&) and OR (||).
Logical AND (&&)
- Both conditions must be true for the result to be true;
- If either condition is false, the result is false.
Example: If you want to check if a number is both positive and even:
val number = 8
if (number > 0 && number % 2 == 0) {
println("Number is positive and even.")
} else {
println("Number is not both positive and even.")
}
number > 0checks if the number is positive;number % 2 == 0checks if the number is even;- Both must be true for the message to print "Number is positive and even.".
Logical OR (||)
- At least one condition must be true for the result to be true;
- The result is false only if both conditions are false.
Example: If you want to check if a number is either negative or zero:
val number = -3
if (number < 0 || number == 0) {
println("Number is negative or zero.")
} else {
println("Number is positive.")
}
number < 0checks if the number is negative;number == 0checks if the number is zero;- If either is true, the message prints "Number is negative or zero.".
Key Points
- Use
&&when all conditions must be true; - Use
||when at least one condition must be true; - Combine these operators to create flexible and powerful checks in your programs.
Everything was clear?
Thanks for your feedback!
Section 1. Chapter 4
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat
Section 1. Chapter 4