A Tricky Java Question
Here’s a super tricky Java interview question that messes with developer intuition:
❓ Weird Question:
“What will be printed when executing the following code?”
import java.util.*;
public class TrickyJava { public static void main(String[] args) { List list = Arrays.asList("T-Rex", "Velociraptor", "Dilophosaurus"); list.replaceAll(s -> s.toUpperCase()); System.out.println(list); } }
The Trap:
At first glance, everything looks normal:
Arrays.asList(...)
creates a List
.
replaceAll(...)
is a method in List that modifies elements using a function.
Strings are converted to uppercase.
Most developers will expect this output:
[T-REX, VELOCIRAPTOR, DILOPHOSAURUS]
But surprise! This code sometimes throws an UnsupportedOperationException
.
✅ Correct Answer:
The output depends on the JVM implementation!
It might work and print:
[T-REX, VELOCIRAPTOR, DILOPHOSAURUS]
Or it might crash with:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList$Itr.remove(AbstractList.java:572)
at java.util.AbstractList.remove(AbstractList.java:212)
at java.util.AbstractList$ListItr.remove(AbstractList.java:582)
at java.util.List.replaceAll(List.java:500)
Why?
Arrays.asList(...)
does not return a regular ArrayList
, but rather a fixed-size list backed by an array.
The replaceAll(...)
method attempts to modify the list in-place, which is not allowed for a fixed-size list.
Some JVM implementations optimize this internally, making it work, but it is not guaranteed to succeed.
Key Takeaways
Arrays.asList(...)
returns a fixed-size list, not a modifiable ArrayList
.
Modifying it directly (e.g., add()
, remove()
, replaceAll()
) can fail with UnsupportedOperationException
.
Behavior depends on the JVM implementation and internal optimizations.
How to Fix It?
To ensure safe modification, wrap the list in a mutable ArrayList
:
List list = new ArrayList<>(Arrays.asList("T-Rex", "Velociraptor", "Dilophosaurus"));
list.replaceAll(s -> s.toUpperCase());
System.out.println(list); // ✅ Always works!