Consider the following Kotlin code snippet:
val result = 3 + 4 * 2 / (1 - 5) % 2 println(result)
What will be printed?
val result = 3 + 4 * 2 / (1 - 5) % 2 println(result)
Remember the order: parentheses, multiplication/division/modulus, then addition/subtraction.
First, (1 - 5) = -4.
Then, 4 * 2 = 8.
Next, 8 / -4 = -2.
Then, -2 % 2 = 0 (because -2 mod 2 is 0 in Kotlin).
Finally, 3 + 0 = 3.
Given this Kotlin code:
var x = 10 x += 3 * 2 - 4 / 2
What is the value of x after running this?
var x = 10 x += 3 * 2 - 4 / 2 println(x)
Calculate multiplication and division before addition and subtraction.
3 * 2 = 6
4 / 2 = 2
Then 6 - 2 = 4
x += 4 means x = 10 + 4 = 14
Analyze this Kotlin code:
val a = true val b = false val c = 5 val d = 10 val result = a && b || c < d && !b println(result)
What is the output?
val a = true val b = false val c = 5 val d = 10 val result = a && b || c < d && !b println(result)
Remember that && has higher precedence than ||, and ! has highest precedence.
!b = !false = true
a && b = true && false = false
c < d = 5 < 10 = true
c < d && !b = true && true = true
Then false || true = true
Consider this Kotlin snippet:
var x = 5 val y = x++ * 2 + --x println(y)
What will be printed?
var x = 5 val y = x++ * 2 + --x println(y)
Remember post-increment returns the value before increment, pre-decrement decrements before use.
Initial x=5
x++ returns 5, then x becomes 6
--x decrements x to 5, then returns 5
So y = 5 * 2 + 5 = 10 + 5 = 15
Analyze this Kotlin code:
var a = 2 var b = 3 var c = 4 val result = a + b * c / a - b % c println(result)
What will be printed?
var a = 2 var b = 3 var c = 4 val result = a + b * c / a - b % c println(result)
Follow operator precedence: multiplication/division/modulus before addition/subtraction.
b * c = 3 * 4 = 12
12 / a = 12 / 2 = 6
b % c = 3 % 4 = 3
Then a + 6 - 3 = 2 + 6 - 3 = 5