Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Combining Multiple Conditions | Boolean Expressions and Logical Conditions
Control Flow in Kotlin

bookCombining Multiple Conditions

Sveip for å vise menyen

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 > 0 checks if the number is positive;
  • number % 2 == 0 checks 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 < 0 checks if the number is negative;
  • number == 0 checks 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.
question mark

Which expression is true only if both a is greater than 5 and b is less than 10 in Kotlin?

Velg det helt riktige svaret

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 1. Kapittel 4

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 1. Kapittel 4
some-alt