KOTLIN Tutorial



OPERATORS IN KOTLIN


Operators in Kotlin

Kotlin supports a wide range of operators to perform various operations such as arithmetic, comparison, logic, and assignment. Operators are symbols that tell the compiler to perform specific mathematical or logical operations.

1. Arithmetic Operators

Used for basic mathematical operations:

  • + : Addition
  • - : Subtraction
  • * : Multiplication
  • / : Division
  • % : Modulus (Remainder)
fun main() {
    val a = 10
    val b = 3
    println("a + b = ${a + b}")
    println("a - b = ${a - b}")
    println("a * b = ${a * b}")
    println("a / b = ${a / b}")
    println("a % b = ${a % b}")
}
  

2. Relational Operators

Used to compare two values:

  • == : Equal to
  • != : Not equal to
  • > : Greater than
  • < : Less than
  • >= : Greater than or equal to
  • <= : Less than or equal to
fun main() {
    val x = 5
    val y = 8
    println(x == y)
    println(x != y)
    println(x < y)
    println(x >= y)
}
  

3. Logical Operators

Used to combine multiple conditions:

  • && : Logical AND
  • || : Logical OR
  • ! : Logical NOT
fun main() {
    val a = true
    val b = false
    println(a && b) // false
    println(a || b) // true
    println(!a)     // false
}
  

4. Assignment Operators

Used to assign or update values:

  • = : Assign
  • += : Add and assign
  • -= : Subtract and assign
  • *= : Multiply and assign
  • /= : Divide and assign
  • %= : Modulus and assign
fun main() {
    var num = 10
    num += 5  // 15
    num -= 3  // 12
    num *= 2  // 24
    num /= 4  // 6
    println(num)
}
  

5. Unary Operators

Used to increment, decrement or negate values:

  • ++ : Increment
  • -- : Decrement
  • + : Unary plus
  • - : Unary minus
fun main() {
    var a = 4
    println(++a)  // 5
    println(--a)  // 4
    println(+a)   // 4
    println(-a)   // -4
}
  

Summary

  • Arithmetic → For math calculations
  • Relational → For comparisons
  • Logical → For boolean operations
  • Assignment → For setting and updating values
  • Unary → For modifying a single value

Next Topic: Control Flow in Kotlin →


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review