Start learning free

LESSON 68 OF 348 · CONDITIONAL STATEMENTS

Comparison Operators in Kotlin

Lesson Read the full explanation

When writing if statements, we usually compare two values using one or more comparison operators:

Operator Name Examples
== Equal  x == 5,  x == y
!= Not equal  x != 3,  x != y
> Greater than  x > 5,  x > y
< Less than  x < 8,  x < y
>= Greater than or equal to  x >= 4,  x >= y
<= Less than or equal to  x <= 3,   x <= y

For example:

10 == 10 // Evaluates to true
3 < 2 // Evaluates to false
15 >= 15 // Evaluates to true
17 != 12 // Evaluates to true

We usually use these operators with variables:

val a = 10
val b = 15

if (a == b) {
    println("a is equal to b")
}
if (a < b) {
    println("a is less than b")
}

The first condition is not satisfied since 10 == 15 evaluates to false.

The second condition is satisfied since 10 < 15 evaluates to true.

The code above prints "a is less than b".


Assignment
Follow the Coding Tutorial and let's play with comparison operators.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    KOTLIN · CONDITIONAL STATEMENTS

    Comparison Operators in Kotlin, explained

    What comparison operators do

    A comparison operator looks at two values and answers a yes-or-no question about them. The answer is always a Boolean: true or false. That makes comparisons the natural fuel for if statements, which need a Boolean condition.

    OperatorMeaningExample
    ==equal tox == 5
    !=not equal tox != 3
    >greater thanx > y
    <less thanx < 8
    >=greater than or equal tox >= 4
    <=less than or equal tox <= y

    Each of these expressions produces a value you can print, store in a variable or use as a condition:

    10 == 10 // true
    3 < 2 // false
    15 >= 15 // true
    17 != 12 // true
    

    Using them with variables

    Comparisons are most useful with variables, where the result depends on the data:

    val a = 10
    val b = 15
    
    if (a == b) {
        println("a is equal to b")
    }
    if (a < b) {
        println("a is less than b")
    }
    

    The first condition is 10 == 15, which is false, so its block is skipped. The second is 10 < 15, which is true. The program prints a is less than b.

    Storing and reusing a result

    Because a comparison is an ordinary expression, you can keep its result in a variable and use the name later. This often reads better than repeating a long condition:

    val age = 21
    val isAdult = age >= 18
    println(isAdult)
    println(age != 21)
    

    This prints true and then false. The variable isAdult has type Boolean, and you can write if (isAdult) directly, with no need to compare it to true.

    The operators also compare the value a variable holds right now, not the variable itself. If the variable changes later, an earlier stored result does not update. Run the comparison again when the data changes.

    Details worth knowing in Kotlin

    • == compares contents. For strings, "a" == "a" is true because Kotlin calls equals for you. Kotlin has a separate operator, ===, for comparing whether two references are the same object. You rarely need it.
    • = is not ==. A single = assigns a value. Using it inside an if condition is a compile error.
    • Strings can be ordered. "abc" < "abd" is true, since strings compare alphabetically, character by character.
    • Be careful with mixed number types. < works between an Int and a Double, but == does not: with val d: Double = 5.0, writing d == 5 gives the compile error "operator '==' cannot be applied to 'Double' and 'Int'". Write d == 5.0 instead.
    • Comparisons don't chain. In maths you write 1 < x < 10, but in Kotlin 1 < x is evaluated first and produces a Boolean, which then can't be compared with 10. The compiler reports a type mismatch. To test two conditions at once, join them with &&, as in x > 1 && x < 10, or write x in 2..9.
    • Decimal numbers are approximate. 0.1 + 0.2 == 0.3 is false, because the sum is actually 0.30000000000000004. Avoid testing decimal results with ==.

    The exercise

    You start with val grade = 8. The task is to print Failed the test when the grade is below 5 and Passed the test otherwise. Work through it in three moves:

    1. Write an if that checks grade < 5. The < operator is true only when the left side is strictly smaller, so a grade of exactly 5 does not count as failed.
    2. Inside it, print "Failed the test" with println.
    3. Add an else branch that prints "Passed the test". It covers every grade of 5 or more, so it needs no condition of its own.

    Put together:

    val grade = 8
    
    if (grade < 5) {
        println("Failed the test")
    } else {
        println("Passed the test")
    }
    

    With grade equal to 8, the condition 8 < 5 is false, so the program prints Passed the test. With a grade of 4 it prints Failed the test. With 5, the boundary value, it prints Passed the test.

    Common mistakes

    • Using <= when you mean <. Then a grade of 5 would be reported as failed. The boundary value is where these mistakes show, so always test it.
    • Reversing the operator. grade > 5 mixes up the two branches. Say the condition aloud, "grade is less than 5", before you write it.
    • Typing => or =<. The correct forms are >= and <=, with the angle bracket first.

    Key takeaways

    • Comparison operators produce a Boolean.
    • == and != test equality; <, >, <= and >= test order.
    • The = operator assigns and == compares.
    • Check the boundary values, such as a grade of exactly 5.
    • To test a range, combine two comparisons with && rather than chaining them.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free