Create An Immutable Class In Java

Learn about how to create an Immutable class in java and its benefits.

Rakshit Shah
BeingCoders

--

Immutable class cover image | Image by Author Rakshit Shah

Table of Contents

  1. Overview
  2. Usage of Immutable class
  3. Steps to create an Immutable class
  4. Exploring Existing Immutable classes in Java
  5. Examples with/without Mutable/Immutable class
  6. Conclusion

1. Overview

Immutable class, once an object is instantiated, we cannot modify its content. In Java, all the wrapper classes (let’s say, Integer, Short, Boolean, Byte, etc.) and String, etc. classes — are immutable. We can create our own immutable class as well.

An object is immutable if its state cannot be modified after construction. Immutable objects don’t expose any way for other objects to modify their state; the object’s fields are initialized only once inside the constructor and never change again.[³]

Always remember that,

  • Primitive data types — includes byte, short, int, long, float, double, boolean, and char.
  • Non-primitive data types — such as String, Arrays, Interfaces, and Classes.

--

--

Rakshit Shah
BeingCoders

Computer Engineer | Foodie | Traveler| Love to learn & earn new things in daily life.