What is immutability in Java?

Immutability in Java refers to the property of an object whose state cannot be modified after it is created. In Java, immutable objects are typically instances of classes where the attributes defined within the object cannot be changed. The most commonly used immutable class in Java is the String class.

When you create an immutable object, any changes made to that object will result in the creation of a new object rather than modifying the original. This characteristic is beneficial as it provides simplicity and thread-safety in applications.

Here is an example of creating an immutable class in Java:

public final class ImmutablePoint { private final int x; private final int y; public ImmutablePoint(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } }

Immutability Immutable Objects Java Thread Safety String Class