what is immutable in java

what is immutable in java

1 year ago 46
Nature

In Java, an object is considered immutable if its state cannot change after it is constructed. Immutable objects are widely accepted as a sound strategy for creating simple, reliable code, especially in concurrent applications, as they cannot be corrupted by thread interference or observed in an inconsistent state.

Some examples of immutable classes in Java include the String class and all the wrapper classes (like Integer, Boolean, Byte, Short) . To create an immutable class in Java, you need to follow some general principles:

  • Declare the class as final so it can’t be extended.
  • Declare all fields as private so that direct access is not allowed.
  • Declare all fields as final so that their values can be assigned only once.
  • Dont provide any setters or in simpler terms, there should be no option to change the value of the instance variable.

Creating an immutable class in Java can be achieved by using deep copy to initialize the object.

Read Entire Article