Bird
0
0

What will be the output of this Kotlin code?

medium📝 Predict Output Q4 of 15
Kotlin - Collections Fundamentals
What will be the output of this Kotlin code?
val list = mutableListOf(1, 2, 3)
list.add(4)
println(list)
A[1, 2, 3]
B[1, 2, 3, 4]
C[4, 1, 2, 3]
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Understand mutableListOf() and add()

    mutableListOf creates a mutable list; add(4) appends 4 to the list.
  2. Step 2: Predict the printed list

    After adding 4, the list contains [1, 2, 3, 4], so println outputs this.
  3. Final Answer:

    [1, 2, 3, 4] -> Option B
  4. Quick Check:

    Mutable list after add() = [1, 2, 3, 4] [OK]
Quick Trick: mutableListOf() allows add() to change list [OK]
Common Mistakes:
MISTAKES
  • Thinking list is immutable
  • Expecting add() to fail
  • Confusing order of elements

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes