← Back to libraryQuestion 26 of 273
JavaIntermediate

Immutable Classes

📖 Detailed Explanation:

An immutable class is a class whose state CANNOT be changed after it is created. Examples: String, all Wrapper classes (Integer, Boolean). To create an immutable class: make it final, make all fields private and final, provide no setters, and never expose mutable internal objects. Immutable objects are thread-safe by default.

🌍 Real-World Example:

A permanent record in a ledger. Once a transaction is timestamped and sealed, that specific entry can never be altered.

🎯 Scenario-Based Interview Question:

If an immutable class has a field that references a mutable object (like java.util.Date), how do you keep it truly immutable?