Logical Operators
Deslize para mostrar o menu
Combining Boolean Expressions with Logical Operators
You can combine multiple Boolean expressions in Kotlin using logical operators. These operators let you build more complex conditions by connecting simple true/false statements.
Logical Operators in Kotlin
- AND (
&&): Returnstrueonly if both expressions aretrue; - OR (
||): Returnstrueif at least one expression istrue; - NOT (
!): Reverses the value of a Boolean expression.
Example: Checking Multiple Conditions
Suppose you want to check if a number is positive and even. You can combine the two checks using the && operator:
package com.example
fun main() {
val number = 8
val isPositive = number > 0
val isEven = number % 2 == 0
val result = isPositive && isEven
println(result) // Prints: true
}
Example: Using OR (||)
You can also check if a number is either negative or zero:
package com.example
fun main() {
val number = -1
val isNegative = number < 0
val isZero = number == 0
val result = isNegative || isZero
println(result) // Prints: true
}
Example: Using NOT (!)
To reverse a Boolean value, use the ! operator:
package com.example
fun main() {
val isSunny = false
val stayIndoors = !isSunny
println(stayIndoors) // Prints: true
}
You can use these operators to create flexible, readable conditions without relying on if/else statements.
Tudo estava claro?
Obrigado pelo seu feedback!
Seção 1. Capítulo 3
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo
Seção 1. Capítulo 3