Start learning free

LESSON 74 OF 348 · CONDITIONAL STATEMENTS

The And Operator (&&) in Kotlin

Lesson Read the full explanation

Sometimes you will need to test more than one thing at a time. The logical and operator (&&) returns true if and only if both conditions to the left and right of it are true. For example:

10 == 10 && 7 < 10 // Evaluates to true

We have two conditions separated by && operator:

  • 10 == 10, which evaluates to true
  • 7 < 10, which evaluates to true
As both conditions evaluate to true, the entire line will evaluate to true

An example inside an if statement:

val x = 10
if (x != 7 && 12 < x) { // Evaluates to false
    println("This is true!")
}

Inside the if, we have two conditions separated by && operator:

  • x != 7, equivalent to 10 != 7, which evaluates to true
  • 12 < x, equivalent to 12 < 10, which evaluates to false
As one of the conditions evaluates to false, the entire statement will evaluate to false, and so the program prints nothing.

Assignment
Follow the Coding Tutorial and play with the and operator.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    KOTLIN · CONDITIONAL STATEMENTS

    And Operator in Kotlin, explained

    What && does

    Sometimes one test isn't enough. You may want to run code only when the weather is sunny and the temperature is high. The logical and operator, written &&, joins two Boolean expressions into one. The result is true only when both sides are true. If either side is false, the whole expression is false.

    LeftRightLeft && Right
    truetruetrue
    truefalsefalse
    falsetruefalse
    falsefalsefalse

    Here is an example with two comparisons:

    10 == 10 && 7 < 10 // true
    

    The left side, 10 == 10, is true. The right side, 7 < 10, is also true. Both hold, so the whole line is true.

    Using && in an if

    In practice, && sits inside the condition of an if:

    val x = 10
    if (x != 7 && 12 < x) {
        println("This is true!")
    }
    

    With x equal to 10, the first part x != 7 is true, but the second part 12 < x is false. One failure is enough to make the whole condition false, so the block is skipped and the program prints nothing.

    Each side of && is a complete condition. Comparisons are evaluated before &&, so you don't need parentheses around them. You may chain more than two: a && b && c is true only when all three are.

    Short-circuit evaluation

    Kotlin evaluates && from left to right and stops as soon as the answer is known. If the left side is false, the result must be false, so the right side is never evaluated. This is called short-circuiting, and it makes some checks safe:

    fun check(label: String, v: Boolean): Boolean {
        println("checking $label")
        return v
    }
    
    println(check("left", false) && check("right", true))
    

    This prints checking left and then false. The function for the right side never runs. With true on the left, both checks run and the result is true.

    The same rule lets you guard a risky test with a safe one. In list != null && list.size > 0, the size is only read when the list is not null. Kotlin even understands this: inside the right side, it treats list as non-null.

    The exercise

    You start with two variables:

    val weather = "rainy"
    val temperature = 90
    

    The task has two steps.

    1. Write an if with the condition weather == "sunny" && temperature > 85, and print "Going to the beach" inside it. The message should only appear when both checks pass. In Kotlin, == on strings compares their text, so weather == "sunny" does what you expect.
    2. Add an else branch that prints "Learning to code", so the program still answers when either check fails.
    val weather = "rainy"
    val temperature = 90
    
    if (weather == "sunny" && temperature > 85) {
        println("Going to the beach")
    } else {
        println("Learning to code")
    }
    

    It's hot, but the weather is "rainy", so the left check fails and the program prints Learning to code. Change weather to "sunny" and it prints Going to the beach. Keep "sunny" but lower the temperature to 70 and the second check fails, so you are back to Learning to code.

    Always test both sides of a rule like this one: the case where both parts hold, and the cases where only one of them does.

    Keeping long conditions readable

    When a condition grows, give each part a name. The names turn the if into a sentence:

    val isSunny = weather == "sunny"
    val isHot = temperature > 85
    
    if (isSunny && isHot) {
        println("Going to the beach")
    }
    

    The behaviour is the same as before. Each variable holds a Boolean, and && combines them. You can also split a long condition over several lines, as long as each line except the last ends with && so that Kotlin knows the expression continues.

    Common mistakes

    • A single &. Kotlin doesn't use & for logical and. Use two.
    • Dropping the second comparison. Writing weather == "sunny" && 85 does not compile, because 85 is not a Boolean. Each side needs its own full comparison, such as temperature > 85.
    • Using >= when the rule says more than. A temperature of exactly 85 must not go to the beach.
    • Mixing up the words. "Sunny and hot" needs &&. Using the or operator || would let rainy days at 90 degrees through.

    Key takeaways

    • a && b is true only when both a and b are true.
    • Each side of && is its own complete condition.
    • If the left side is false, the right side isn't evaluated.
    • Strings are compared with == in Kotlin.
    • Naming the parts of a condition keeps long if statements easy to read.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free