What is immutability in Java?
AI-Powered Answer
✓ Answered
Immutability in Java refers to the concept that once an object is created, its internal state cannot be modified. Any operation that appears to modify an immutable object will actually result in the creation of a new object with the modified state, leaving the original object unchanged.
What is an Immutable Object?
An immutable object is an instance whose state cannot be changed after it is constructed. This means that all its fields are effectively read-only after initialization. If you need to change the 'value' represented by an immutable object, you must create a new immutable object with the desired new value.
Why is Immutability Important?
- Thread Safety: Immutable objects are inherently thread-safe because their state cannot be changed by multiple threads concurrently, eliminating the need for synchronization.
- Simplicity: They are easier to reason about and design with, as their state is predictable and constant once created.
- Easier Caching: Since their state never changes, immutable objects can be safely cached and reused, potentially improving performance.
- Security: Immutable objects cannot be maliciously altered after creation, making them useful for sensitive data.
- Fewer Side Effects: Methods that operate on immutable objects cannot produce unexpected side effects on the object itself.
How to Create Immutable Classes in Java
- Declare the class as
finalto prevent it from being subclassed. This ensures that no subclass can violate immutability. - Make all fields
privateandfinal.privaterestricts direct access, andfinalensures they are initialized once and never reassigned. - Don't provide setter methods for any fields.
- If the class has mutable object fields (e.g.,
Date,ArrayList), make sure to handle them with 'defensive copying' in the constructor and any getter methods. This means creating a new instance of the mutable object rather than directly assigning or returning a reference to the internal mutable object. - If the class has mutable fields, ensure that methods that appear to modify the object return a new instance with the modified state, rather than changing the current instance.
Examples of Immutable Classes in Java
java.lang.String: The most well-known example. Any operation likesubstring()orreplace()returns a newStringobject.- Wrapper classes (
Integer,Long,Double,Boolean, etc.): These classes wrap primitive types and are immutable. java.math.BigIntegerandjava.math.BigDecimal: Used for arbitrary-precision arithmetic.- Date and Time API (
java.time.LocalDate,LocalTime,LocalDateTime,ZonedDateTime): All classes in thejava.timepackage are immutable.
Code Example: Simple Immutable Class
java
public final class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
// No setter methods
// Example of a method that 'modifies' but returns a new instance
public Point move(int deltaX, int deltaY) {
return new Point(this.x + deltaX, this.y + deltaY);
}
@Override
public String toString() {
return "Point(" + x + ", " + y + ")";
}
public static void main(String[] args) {
Point p1 = new Point(1, 2);
System.out.println("Original point: " + p1); // Point(1, 2)
Point p2 = p1.move(3, 4);
System.out.println("Moved point: " + p2); // Point(4, 6)
System.out.println("Original point after move: " + p1); // Point(1, 2) - p1 is unchanged
}
}