Immutability — Concept Check
Questions on Immutability. Immutable objects cannot be changed after construction — they are inherently thread-safe, cacheable, and safe as HashMap keys.
Questions in this quiz
8 questions on Immutability — Concept Check. Work through them here, then start the quiz to answer them and see your score.
1.You have a class storing a list of user actions. How can you ensure this list remains immutable?
- AUse a synchronized list.
- BDeclare the list as final.
- CMake a defensive copy of the list in the constructor.
- DProvide a setter for the list.
2.A developer claims their class is immutable because it has no setters. What might be wrong with this claim?
- AThe class might not be final.
- BThe class might leak mutable references.
- CThe constructor might not be private.
- DThe class might not have private fields.
3.In Java, why is a String considered immutable?
- AIt cannot be changed after creation.
- BIt uses a private constructor.
- CIt has synchronized methods.
- DIt is declared as final.
4.A class uses java.util.Date for timestamps. What should you do to ensure immutability?
- AProvide getters only.
- BUse synchronized blocks around Date objects.
- CDeclare Date objects as final.
- DUse defensive copies of Date objects.
5.Why might using a mutable object as a HashMap key lead to issues?
- AHashMap does not support mutable keys.
- BIt slows down retrieval.
- CThe object's hash code might change.
- DIt requires more memory.
6.A developer uses List.copyOf to store a list in an immutable class. Why is this beneficial?
- AIt simplifies code readability.
- BIt creates an unmodifiable copy of the list.
- CIt improves performance.
- DIt reduces memory usage.
7.A class is declared final and has no setters. Is it guaranteed to be immutable?
- AYes, as long as fields are private.
- BNo, it might still leak mutable references.
- CYes, final and no setters ensure immutability.
- DNo, it needs synchronized methods.
8.Why is java.time.Instant preferred over java.util.Date for immutability?
- AInstant is inherently immutable.
- BInstant is faster.
- CInstant uses less memory.
- DInstant is more readable.