Welcome back to CodeYourCraft! Today, we're diving into the fascinating world of Kotlin Logical Operators. These are the building blocks for creating complex conditions and decision-making in your code. Let's get started!
Logical operators allow us to combine multiple conditions into a single expression. They help us to write more efficient and expressive code. In Kotlin, there are three main logical operators:
&& (Logical AND)|| (Logical OR)! (Logical NOT)&&) 💡The && operator checks if both conditions are true. If either condition is false, the entire expression evaluates to false.
Here's an example:
fun main() {
val age = 20
val isStudent = true
if (age >= 18 && isStudent) {
println("You can vote!")
}
}In this example, the user can vote only if they are 18 or older AND a student. If the age is less than 18 or the user is not a student, the message "You can vote!" will not be printed.
In the following code, what will be printed?
||) 💡The || operator checks if at least one condition is true. If both conditions are false, the entire expression evaluates to false.
Here's an example:
fun main() {
val age = 16
val isStudent = false
if (age >= 18 || isStudent) {
println("You can vote!")
}
}In this example, the user can vote if they are 18 or older OR a student (regardless of their age). If the age is less than 18 and the user is not a student, the message "You can vote!" will still be printed.
In the following code, what will be printed?
!) 💡The ! operator negates a condition, meaning it changes true to false and false to true.
Here's an example:
fun main() {
val isRaining = true
if (!isRaining) {
println("It's not raining!")
}
}In this example, the message "It's not raining!" will be printed if isRaining is true. If isRaining is false, the message will not be printed.
In the following code, what will be printed?
Now that you've learned about Kotlin logical operators, let's test your knowledge with some practice problems.
fun canDrive(age: Int, hasLicense: Boolean): Boolean {
// Fill in the code here
}fun canAccessWebsite(age: Int, isUsingSchoolIP: Boolean): Boolean {
// Fill in the code here
}Answers:
fun canDrive(age: Int, hasLicense: Boolean): Boolean {
return age >= 18 && hasLicense
}fun canAccessWebsite(age: Int, isUsingSchoolIP: Boolean): Boolean {
return age >= 18 && !isUsingSchoolIP
}Congratulations on learning Kotlin logical operators! Keep practicing, and soon you'll be a coding master. 🚀