Kotlin Operators and Strings
Operators let you calculate and compare values, and strings let you work with text.
Arithmetic Operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Add | 7 + 3 | 10 |
- | Subtract | 7 - 3 | 4 |
* | Multiply | 7 * 3 | 21 |
/ | Divide | 7 / 2 | 3 |
% | Remainder | 7 % 2 | 1 |
When both numbers are Int, division drops the decimal part. Use a Double to keep it:
Example
kotlin
fun main() {
println(7 / 2)
println(7.0 / 2)
println(7 % 2)
var balance = 500
balance += 200 // same as balance = balance + 200
balance -= 50
println(balance)
balance++
println(balance)
}Output
3 3.5 1 650 651
Comparison and Logical Operators
Comparison operators give a Boolean (true or false):
| Operator | Meaning |
|---|---|
== | equal to |
!= | not equal to |
> and < | greater than, less than |
>= and <= | greater or equal, less or equal |
Logical operators join conditions:
&&(and): true only if both sides are true||(or): true if at least one side is true!(not): turns true into false and false into true
Example
kotlin
fun main() {
val age = 20
val hasCnic = true
println(age >= 18 && hasCnic)
println(age < 13 || age > 60)
println(!hasCnic)
}Output
true false false
String Templates
Put a variable inside a string with $. For a calculation or a property, use ${ }:
Example
kotlin
fun main() {
val item = "Biryani"
val price = 350
println("One plate of $item costs Rs $price")
println("Two plates cost Rs ${price * 2}")
println("The word $item has ${item.length} letters")
}Output
One plate of Biryani costs Rs 350 Two plates cost Rs 700 The word Biryani has 7 letters
Useful String Functions
Example
kotlin
fun main() {
val city = " Karachi "
val clean = city.trim()
println(clean)
println(clean.uppercase())
println(clean.lowercase())
println(clean.length)
println(clean[0])
println(clean.contains("chi"))
println(clean.startsWith("Ka"))
println(clean.substring(0, 4))
println(clean.replace("a", "@"))
}Output
Karachi KARACHI karachi 7 K true true Kara K@r@chi
| Function | What it does |
|---|---|
trim() | Removes spaces at the start and end |
uppercase() / lowercase() | Changes the case |
length | Number of characters (a property, no brackets) |
[i] | The character at position i (counting from 0) |
contains() | Checks whether some text is inside |
substring(a, b) | Characters from position a up to, but not including, b |
replace(old, new) | Replaces text |
Strings in Kotlin are immutable: functions like uppercase() return a new string and do not change the original.
Comparing Strings
Use == to check if two strings have the same text. To ignore upper and lower case, use equals with ignoreCase = true:
Example
kotlin
fun main() {
val a = "pakistan"
val b = "Pakistan"
println(a == b)
println(a.equals(b, ignoreCase = true))
}Output
false true
Exercise
Exercise
What does println(17 % 5) print?
