Kotlin Relational Operators

Introduction

Relational operators in Kotlin are used to compare two values. They return a Boolean result (true or false) based on the comparison. These operators are essential for making decisions in your code by evaluating conditions.

Types of Relational Operators

1. == (Equal to)

Checks if two values are equal.

Syntax:

val result = operand1 == operand2

Example:

fun main() {
    val a = 10
    val b = 20
    val c = 10

    println("a == b: ${a == b}")  // Output: false
    println("a == c: ${a == c}")  // Output: true
}

2. != (Not equal to)

Checks if two values are not equal.

Syntax:

val result = operand1 != operand2

Example:

fun main() {
    val a = 10
    val b = 20
    val c = 10

    println("a != b: ${a != b}")  // Output: true
    println("a != c: ${a != c}")  // Output: false
}

3. < (Less than)

Checks if the value on the left is less than the value on the right.

Syntax:

val result = operand1 < operand2

Example:

fun main() {
    val a = 10
    val b = 20

    println("a < b: ${a < b}")  // Output: true
    println("b < a: ${b < a}")  // Output: false
}

4. > (Greater than)

Checks if the value on the left is greater than the value on the right.

Syntax:

val result = operand1 > operand2

Example:

fun main() {
    val a = 10
    val b = 20

    println("a > b: ${a > b}")  // Output: false
    println("b > a: ${b > a}")  // Output: true
}

5. <= (Less than or equal to)

Checks if the value on the left is less than or equal to the value on the right.

Syntax:

val result = operand1 <= operand2

Example:

fun main() {
    val a = 10
    val b = 20
    val c = 10

    println("a <= b: ${a <= b}")  // Output: true
    println("a <= c: ${a <= c}")  // Output: true
    println("b <= a: ${b <= a}")  // Output: false
}

6. >= (Greater than or equal to)

Checks if the value on the left is greater than or equal to the value on the right.

Syntax:

val result = operand1 >= operand2

Example:

fun main() {
    val a = 10
    val b = 20
    val c = 10

    println("a >= b: ${a >= b}")  // Output: false
    println("a >= c: ${a >= c}")  // Output: true
    println("b >= a: ${b >= a}")  // Output: true
}

Conclusion

In this chapter, you learned about relational operators in Kotlin, which are used to compare two values and return a Boolean result. The operators include ==, !=, <, >, <=, and >=. Understanding these operators is crucial for making decisions in your code based on the comparison of values.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top