0
0
Kotlinprogramming~5 mins

Comparison operators in Kotlin

Choose your learning style9 modes available
Introduction

Comparison operators help us check if values are equal or which one is bigger or smaller. This is useful to make decisions in programs.

Checking if a user entered the correct password
Comparing ages to see who is older
Finding out if a number is positive or negative
Deciding if a score is high enough to pass
Sorting items by size or price
Syntax
Kotlin
a == b  // equals
 a != b  // not equals
 a > b   // greater than
 a < b   // less than
 a >= b  // greater than or equal to
 a <= b  // less than or equal to

Use double equals (==) to check if two values are the same.

Use != to check if two values are different.

Examples
This checks if x and y are equal. They are not, so it prints false.
Kotlin
val x = 5
val y = 10
println(x == y)  // false
This checks if a and b are different. They are the same, so it prints false.
Kotlin
val a = 7
val b = 7
println(a != b)  // false
This checks if age is at least 18. It is, so it prints true.
Kotlin
val age = 18
println(age >= 18)  // true
This checks if score is less than 50. It is not, so it prints false.
Kotlin
val score = 75
println(score < 50)  // false
Sample Program

This program checks if the temperature is hot, cold, or exactly 30 degrees using comparison operators.

Kotlin
fun main() {
    val temperature = 30
    val isHot = temperature > 25
    val isCold = temperature < 15
    println("Is it hot? $isHot")
    println("Is it cold? $isCold")
    println("Is temperature exactly 30? ${temperature == 30}")
}
OutputSuccess
Important Notes

Comparison operators return a Boolean value: true or false.

Use parentheses {} inside strings to show the result of comparisons.

Summary

Comparison operators help compare two values.

They return true or false depending on the comparison.

Common operators: ==, !=, >, <, >=, <=.