Operators
Operators in Kotlin
Operators are symbols used to perform operations.
Example:
val result = 10 + 20Here + is an operator.
1. Arithmetic Operators
Arithmetic operators are used for mathematical calculations.
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Addition | 10 + 5 | 15 |
- | Subtraction | 10 - 5 | 5 |
* | Multiplication | 10 * 5 | 50 |
/ | Division | 10 / 5 | 2 |
% | Remainder | 10 % 3 | 1 |
Example
fun main() {
val a = 10
val b = 3
println("Addition: ${a + b}")
println("Subtraction: ${a - b}")
println("Multiplication: ${a * b}")
println("Division: ${a / b}")
println("Remainder: ${a % b}")
}Output
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3
Remainder: 12. Comparison Operators
Comparison operators compare two values and return true or false.
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | a == b |
!= | Not equal to | a != b |
> | Greater than | a > b |
< | Less than | a < b |
>= | Greater than or equal | a >= b |
<= | Less than or equal | a <= b |
-
Example
fun main() {
val age = 20
println(age >= 18)
println(age < 18)
}Output
true
falseReal-Life Example
fun main() {
val age = 20
if (age >= 18) {
println("Eligible for driving license")
} else {
println("Not eligible")
}
}Output
Eligible for driving license3. Logical Operators
| Operator | Name | Meaning |
|---|---|---|
&& | AND | All conditions must be true |
| `\ | \ | ` |
! | NOT | Reverses the result |
AND Example
fun main() {
val age = 20
val hasIdCard = true
if (age >= 18 && hasIdCard) {
println("Entry allowed")
} else {
println("Entry not allowed")
}
}Output
Entry allowedOR Example
fun main() {
val hasEmail = false
val hasPhone = true
if (hasEmail || hasPhone) {
println("User can login")
} else {
println("User cannot login")
}
}Output
User can loginNOT Example
fun main() {
val isLoggedIn = false
if (!isLoggedIn) {
println("Please login")
}
}Output
Please login4. Assignment Operators
Assignment operators are used to assign or update values.
| Operator | Meaning | Example |
|---|---|---|
= | Assign value | x = 10 |
+= | Add and assign | x += 5 |
-= | Subtract and assign | x -= 5 |
*= | Multiply and assign | x *= 2 |
/= | Divide and assign | x /= 2 |
%= | Remainder and assign | x %= 2 |
Example
fun main() {
var count = 10
count += 5
println("After += : $count")
count -= 3
println("After -= : $count")
count *= 2
println("After *= : $count")
count /= 4
println("After /= : $count")
}Output
After += : 15
After -= : 12
After *= : 24
After /= : 65. Increment and Decrement Operators
| Operator | Meaning |
|---|---|
++ | Increase by 1 |
-- | Decrease by 1 |
Example
fun main() {
var count = 5
count++
println(count)
count--
println(count)
}Output
6
5