Bird
0
0

What will be the output of this Kotlin code?

medium📝 Predict Output Q5 of 15
Kotlin - Collections Fundamentals
What will be the output of this Kotlin code?
val arr = IntArray(3) { it * 2 }
println(arr.joinToString(","))
A1,2,3
B0,2,4
C2,4,6
D0,1,2
Step-by-Step Solution
Solution:
  1. Step 1: Understand the initializer lambda for IntArray

    Each element is initialized as its index multiplied by 2: 0*2=0, 1*2=2, 2*2=4.
  2. Step 2: Check the printed output format

    joinToString(",") joins elements with commas, so output is "0,2,4".
  3. Final Answer:

    0,2,4 -> Option B
  4. Quick Check:

    Initializer with index * 2 = 0,2,4 [OK]
Quick Trick: Initializer lambda uses index 'it' for values [OK]
Common Mistakes:
MISTAKES
  • Assuming values start at 1
  • Confusing multiplication with addition
  • Wrong join separator

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes