0
0
Kotlinprogramming~5 mins

Operator precedence in Kotlin

Choose your learning style9 modes available
Introduction
Operator precedence tells the computer which math or logic steps to do first when there are many in one line.
When you write math calculations with many operators like +, -, *, / in one line.
When you combine logic checks like && and || in one condition.
When you want to make sure your code does steps in the right order without extra parentheses.
When you read code and want to understand how the computer will solve the expression.
When you want to avoid mistakes by knowing which operator acts first.
Syntax
Kotlin
val result = 3 + 4 * 2
val check = true || false && false
Multiplication (*) and division (/) happen before addition (+) and subtraction (-).
Logical AND (&&) happens before logical OR (||).
Examples
Multiplication happens first, so 4 * 2 = 8, then 3 + 8 = 11.
Kotlin
val result = 3 + 4 * 2
Parentheses change order: 3 + 4 = 7, then 7 * 2 = 14.
Kotlin
val result = (3 + 4) * 2
AND (&&) happens before OR (||), so false && false = false, then true || false = true.
Kotlin
val check = true || false && false
Parentheses change order: true || false = true, then true && false = false.
Kotlin
val check = (true || false) && false
Sample Program
This program shows how operator precedence changes results. Multiplication and AND happen before addition and OR unless parentheses change the order.
Kotlin
fun main() {
    val a = 5 + 3 * 2
    val b = (5 + 3) * 2
    val c = true || false && false
    val d = (true || false) && false
    println("a = $a")
    println("b = $b")
    println("c = $c")
    println("d = $d")
}
OutputSuccess
Important Notes
Use parentheses to make your code clear and avoid mistakes.
Remember that multiplication and division have higher precedence than addition and subtraction.
Logical AND (&&) is checked before logical OR (||).
Summary
Operator precedence decides which parts of an expression run first.
Multiplication and division come before addition and subtraction.
Logical AND runs before logical OR.
Parentheses can change the order to what you want.