An immutable class in Java is a class whose objects cannot be modified after creation.
In simple words:
Once an immutable object is created, its state and data remain permanently unchanged.
Why Immutable Classes are Important?
Immutable classes help:
- Improve security
- Support thread safety
- Prevent accidental modification
- Improve caching performance
- Make applications more reliable
Real-Time Example
Think about:
- Aadhaar number
- PAN number
- Transaction ID
- Order ID
Once created, these values should never change.
Immutable Object Flow Diagram
Object Created
|
v
State Assigned Once
|
v
Modification Not Allowed
Example of Immutable Class
final class Employee {
private final int id;
private final String name;
Employee(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
Why This Class is Immutable?
- Class is final
- Variables are private
- Variables are final
- No setter methods
- Values assigned only once
Immutable Class Internal Working
Object Created
|
v
Constructor Initializes Values
|
v
Values Locked Permanently
Main Rules to Create Immutable Class
- Declare class as final
- Make all fields private
- Make all fields final
- Initialize fields through constructor
- Do not provide setter methods
- Return defensive copies for mutable objects
Why Class Should be final?
To prevent inheritance.
Problem Without final Class
class Employee {
}
Child class may modify behavior and break immutability.
Why Variables Should be private?
To prevent direct external modification.
Invalid Example
public int id;
Anyone can modify it directly.
Why Variables Should be final?
To ensure values are assigned only once.
Example
final int id = 101;
Why No Setter Methods?
Setter methods allow object modification.
Invalid Example
public void setName(String name) {
this.name = name;
}
Why Dangerous?
Object state can change after creation.
Immutable Class Memory Flow
Object Created in Heap
|
v
State Initialized Once
|
v
Read-Only Access Allowed
String Class is Immutable
Java String class is one of the best examples of immutable class.
Example
String name = "Java";
name.concat(" Programming");
System.out.println(name);
Output
Java
Why?
concat() creates new object instead of modifying existing object.
String Immutability Flow
Original String
|
+-------> New Modified String Created
|
v
Original Object Remains Unchanged
Immutable Class with Mutable Objects
Special care is needed for mutable objects.
Problem Example
class Employee {
private final Date joiningDate;
}
Why Problem?
Date object is mutable. External code may modify it.
Solution: Defensive Copy
final class Employee {
private final Date joiningDate;
Employee(Date joiningDate) {
this.joiningDate =
new Date(
joiningDate.getTime()
);
}
public Date getJoiningDate() {
return new Date(
joiningDate.getTime()
);
}
}
Defensive Copy Flow
Original Mutable Object
|
v
Copy Created
|
v
Internal Object Protected
Immutable vs Mutable Class
| Feature | Immutable Class | Mutable Class |
|---|---|---|
| Object State | Cannot Change | Can Change |
| Thread Safety | Yes | No |
| Security | High | Lower |
| Performance | Better for Caching | Better for Frequent Updates |
Why Immutable Objects are Thread-Safe?
Because object state never changes, multiple threads can safely access same object.
Thread Safety Diagram
Multiple Threads
|
v
Shared Immutable Object
|
v
No Modification Possible
Immutable Class in Banking Systems
Banking applications use immutable classes for:
- Transaction IDs
- Audit logs
- Security tokens
- Account snapshots
Example
final class TransactionId {
private final String id;
}
Immutable Class in E-Commerce Systems
E-commerce systems use immutable classes for:
- Order IDs
- Invoice details
- Payment tokens
- Audit events
Immutable Classes in Spring Boot
Spring Boot applications use immutable classes for:
- DTOs
- Configuration properties
- Security tokens
- Response objects
Spring Boot Example
public final class UserResponse {
private final String name;
private final String email;
}
Immutable Classes in Microservices
Microservices architectures use immutable classes for:
- Distributed events
- Kafka messages
- REST responses
- Cloud configurations
Why Immutable Objects Improve Performance?
- Safe caching
- No synchronization needed
- Reduced locking overhead
- Better concurrency handling
Immutable Object Cache Flow
Immutable Object
|
v
Shared Safely Across Threads
|
v
No Synchronization Required
Advantages of Immutable Classes
- Thread safety
- Improved security
- Better caching support
- Easier debugging
- Reliable object behavior
Disadvantages of Immutable Classes
- More object creation
- Higher memory usage sometimes
- Complex defensive copying
Common Interview Mistake
Many developers think final class automatically becomes immutable.
Actually:
- Variables must also be private and final.
- No setters should exist.
Another Common Mistake
Many developers think immutable objects cannot contain mutable objects.
Actually:
- Mutable objects are allowed using defensive copies.
Best Practices
- Prefer immutable objects for shared data
- Use defensive copying for mutable fields
- Keep object state minimal
- Use immutable DTOs in APIs
Realtime Enterprise Example
JWT Token Object
final class JwtToken {
private final String token;
private final long expiry;
}
Security tokens should never change after creation.
Immutable Classes and Java Records
Modern Java provides:
record
to simplify immutable object creation.
Example
record Employee(
int id,
String name
) {
}
Why Records are Useful?
- Less boilerplate code
- Immutable by default
- Cleaner syntax
- Better readability
Related Learning Topics
- What is final Keyword in Java
- What is Object Cloning in Java
- Difference Between Shallow Copy and Deep Copy
- Garbage Collection in Java
- What is Polymorphism
- OOPS in Java
- Memory Management in Java
- What is Spring Boot
- What are Microservices
Professional Interview Answer
An immutable class in Java is a class whose objects cannot be modified after creation. To create an immutable class, the class should typically be declared final, fields should be private and final, values should be initialized through constructors, and setter methods should be avoided. Immutable classes improve thread safety, security, caching efficiency, and application reliability because object state never changes after creation. Java String class is a common example of an immutable class. Enterprise applications, Spring Boot services, banking systems, and microservices architectures heavily use immutable objects for DTOs, security tokens, transaction snapshots, and distributed messaging systems.
Frequently Asked Questions
What is an immutable class in Java?
An immutable class is a class whose objects cannot be modified after creation.
Why are immutable classes thread-safe?
Because object state never changes after creation.
Is String immutable in Java?
Yes, String is immutable.
Why should immutable class fields be private?
To prevent direct modification from outside the class.
What is defensive copying?
Defensive copying creates separate copies of mutable objects to protect immutability.