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

bookCombining Multiple Conditions

Glissez pour afficher le 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 > 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?

Sélectionnez la réponse correcte

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 1. Chapitre 4

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

Section 1. Chapitre 4
some-alt