All TalkersCode Topics

Follow TalkersCode On Social Media - A Social Media Network for developers Join Now ➔

Immutable Objects In Java

Last Updated : Jul 1, 2023

Immutable Objects In Java

In this article we will show you the solution of immutable objects in java, an object is said to be immutable if its internal state does not change after it has been fully constructed.

This means that an immutable object's public API assures us that it will act consistently over its entire lifespan.

If we look at the class String, we can see that even while its replace function appears to give us mutable behavior through its API, the original String remains unchanged

The API provides read-only methods; it should never offer any that alter the object's internal state.

Because it is more expensive to create a new object than it is to update an existing object, programmers frequently hesitate to utilize immutable objects.

A few of the efficiencies linked to immutable objects can help to mitigate the impact of object generation, which is frequently overstated.

These include a reduction in overhead brought on by trash collection and the removal of the code required to prevent the corruption of mutable objects.

The subsections that follow take a class with mutable instances and create a class with immutable instances from it.

By doing this, they provide basic guidelines for this type of conversion and illustrate the benefits of immutable objects.

Step By Step Guide On Immutable Objects In Java :-

Simply said, immutable objects are those whose state (or data) cannot change after creation. String and Integer are two JDK examples of immutable objects.

Your programme will be substantially simplified with immutable objects because they are easy to build, test, and use, are thread-safe by default, and have no synchronization problems.

Allow hashCode to use lazy initialization and to cache its return value without the requirement for a copy function Object() { [native code] } or clone.

HashCode also doesn't need to be defensively copied when used as a field. Map keys and Set elements' class invariant is established once during construction and is never tested again (these objects must not change state while in the collection).

Following a few straightforward principles will allow you to create an immutable object:

  • Add no setter methods.
  • Declare all fields to be private and final.
  • Create defensive copies of a field for getter methods if it is changeable.
  • Create a protective copy of an object that was supplied to the function Object() { [native code] } if it has to be assigned to a field.
  • Don't let subclasses substitute their own methods.
  • Declare all fields to be private and final.
  • Private fields cannot be manually changed since they are not accessible from outside the class.

By designating a field as final, you can ensure that any references to primitive values will always point to the same value, and any references to objects will always point to the same reference.

This is insufficient to guarantee the immutability of an object with just private final fields. Here is an illustration of an object with a private final field and a demonstration of how to change the internal state of the object:

public class DateContainer {
  private final Date date;
  public DateContainer() { = new Date();
  public Date getDate() {
    return date;
  DateContainer dateContainer = new DateContainer();
  dateContainer.getDate().setTime(dateContainer.getDate().getTime() + 1000);
  // Now dateContainer date is 1 second after
  1. In the first step we have created a public class DateContainer.
  2. Next step, we will insert a final keyword named date whose value cannot be changed.
  3. Thirdly, we will create a public DataContainer method with keyword to call it.
  4. We will create object of DateContainer using new keyword and a default constructor will be called.
  5. We will print a statement dateContainer.getDate
  6. Then we will insert a statement dateContainer.getDate().setTime(dateContainer.getDate().getTime() + 1000);
  7. Next, Printing dateContainer.getDate
  8. Now the date container date is one second after.
  9. Run the code.

Conclusion :-

So, in this tutorial we learned about creating immutable objects in java by creating final data member with the help of an example. In further tutorial we will study more on immutable classes and objects.

I hope this article on immutable objects in java helps you and the steps and method mentioned above are easy to follow and implement.