Sobes.tech
Junior

What do you understand by immutability in the context of programming in Java?

sobes.tech AI

Answer from AI

Immutability of an object’s state after its creation. Immutable objects do not have methods that modify their internal state. Any operation that could modify it instead returns a new object with the changed state.

Main properties of immutable classes in Java:

  • All fields are marked as final.
  • The class is marked as final (or all constructors are private with factory methods).
  • For primitive type fields, their value is set in the constructor and does not change.
  • For reference type fields, their value is also set in the constructor. Mutator methods (setters) are absent. If a field is a reference to a mutable object, it is copied (deep copy if necessary) during creation or return.

Advantages of immutability:

  • Thread safety: Immutable objects are automatically thread-safe since their state cannot change, eliminating synchronization issues.
  • Simplicity: The object's state is predictable, simplifying debugging and understanding of the code.
  • Caching: Since the state does not change, it is safe to cache the hash code value.
  • Security: Mutable objects can be vulnerable to state changes after creation, which breaks encapsulation.

Example of an immutable class:

// Immutable class example
public final class ImmutablePoint {
    private final int x; // final and private field
    private final int y; // final and private field

    // Constructor initializes fields
    public ImmutablePoint(int x, int y) {
        this.x = x;
        this.y = y;
    }

    // No setters
    public int getX() {
        return this.x;
    }

    public int getY() {
        return this.y;
    }

    // Method returning a new ImmutablePoint object
    public ImmutablePoint translate(int dx, int dy) {
        return new ImmutablePoint(this.x + dx, this.y + dy);
    }
}

Usage example:

// Usage of ImmutablePoint
ImmutablePoint p1 = new ImmutablePoint(1, 2);
ImmutablePoint p2 = p1.translate(3, 4); // Returns a new object

// p1 remains (1, 2)
// p2 is (4, 6)

Examples of built-in immutable classes in Java include String, Integer, Float, and other primitive wrapper classes. Collections also have immutable implementations (e.g., List.of(), Set.of(), Map.of()).

What do you understand by immutability in the context… - sobes.tech