🧱 What Is an Immutable Object?
An immutable object is one whose state cannot be changed after it’s created.
In Java, the most famous immutable class is:
String s = "hello"; // You can't change s
If you try:
s.concat(" world"); // Returns a new String, doesn't modify s
✅ Why Are Immutable Objects Useful?
1. 🧵 Thread Safety Without Synchronization
Immutable objects are inherently thread-safe because:
- No thread can change the object’s state
- So, you don’t need to synchronize access
📌 Perfect for concurrent programming (caches, config objects, keys in maps)
2. 🔄 Simpler to Understand & Debug
- No unexpected side effects
- Once constructed, the object is predictable and consistent
Easier to reason about in large codebases and functional-style code
3. 🧪 Safe to Share and Reuse
- You can freely share immutable objects between threads, methods, and classes
- No one can mess it up
Great for constants, identifiers, configuration values
4. 📚 Can Be Used as Map Keys
Immutable objects are perfect keys for hash-based collections like HashMap
, HashSet
.
Why? Their
hashCode()
andequals()
stay consistent over time.
If you use a mutable key, and it changes after insertion, it can break the map.
5. 🔒 Helps with Defensive Copies
Instead of copying data, just share the same immutable instance.
// If this were mutable, you'd have to make a defensive copy!
public MyClass(User immutableUser) {
this.user = immutableUser; // safe if User is immutable
}
🧠 How to Make an Immutable Class in Java
public final class Person {
private final String name;
private final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public int getAge() { return age; }
}
✅ Key Rules:
- Make the class
final
- Make all fields
private final
- No setters
- Only set values in constructor
- Avoid exposing references to mutable objects (e.g., clone lists/maps)
Examples of Immutable Classes in Java
Class | Notes |
---|---|
String | Most famous one |
Integer | All wrapper types like Boolean , Double |
LocalDate , Instant | From java.time API |
Path , URI , UUID | Many value-based types |
✅ Summary: Why Use Immutables?
Benefit | Why it matters |
---|---|
Thread-safe | No race conditions or locks needed |
Safe to share | Across methods and threads |
Easier to test | No hidden state changes |
Predictable behavior | No side effects |
Safe as Map keys | hashCode() stays stable |