Introduction and Lesson Overview

Greetings! Today, we're studying comparison operators in Kotlin, which are vital for decision-making in coding. Through engaging examples with different data types, we'll grasp the power of these operators. Let's begin our exploration!

Understanding Comparison Operators

Imagine a daily competitive event where we judge who is taller or faster. Replace these with "greater," "lesser," "equal," or "not equal," and you've got comparison operators! Kotlin uses six basic ones:

  1. Equal to (==)
  2. Not equal to (!=)
  3. Greater than (>)
  4. Less than (<)
  5. Greater than or equal to (>=)
  6. Less than or equal to (<=)

Let's explore these through simple examples:

val num1 = 5
val num2 = 10

println(num1 == num2)  //prints: false, as 5 is not equal to 10
println(num1 != num2)  //prints: true, as 5 is not equal to 10
println(num1 > num2)   //prints: false, as 5 is not greater than 10
println(num1 < num2)   //prints: true, as 5 is less than 10
println(num1 >= num2)  //prints: false, as 5 is not greater than or equal to 10
println(num1 <= num2)  //prints: true, as 5 is less than or equal to 10

Comparing 5 and 10 using these operators produces boolean values (true or false).

Applying Comparison Operators on Numbers

Consider two brothers: Harry, who is 12, and Ron, who is 14. We can use age comparison operators to compare their ages:

val ageHarry = 12
val ageRon = 14

println(ageHarry == ageRon)  // prints: false, because Harry and Ron are of different ages
println(ageHarry != ageRon)  // prints: true, as above
println(ageHarry > ageRon)   // prints: false, because Harry is not older than Ron
println(ageHarry < ageRon)   // prints: true, because Harry is younger than Ron
println(ageHarry >= ageRon)  // prints: false, as Harry is not older or as old as Ron
println(ageHarry <= ageRon)  // prints: true, as Harry is younger or as old as Ron (in this case, younger)
Comparison Operators with Booleans

Now, let's compare Boolean variables. Note that == and != are the operators we use here:

val isMorning = true
val isAfternoon = false

println(isMorning == isAfternoon)  // prints: false, as true does not equal false
println(isMorning != isAfternoon)  // prints: true, as true is not equal to false
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal