What Is Mutable Objects, How It Works In Java

What Is Mutable Objects, How It Works In Java

In previous article, I explained about Immutable Objects in Java. Today I will talk about Mutable Objects


Let remember a little about Immutable Objects before we go to Mutable Objects in Java.

Immutable objects are objects whose state cannot be changed once they are created. Once you create an immutable object, you cannot modify its internal state (its fields).

Mutable Object is the inverse concept of Immutable Objects.

Mutable objects are objects whose state can be changed after they are created. You can modify the values of the fields of a mutable object. It mean you can change directly the original value and not create new Objects.


Most classes in Java are mutable by default. For example, ArrayList, HashMap, and custom classes with setter methods are mutable.

Example:

List<String> array = new ArrayList<>();
array.add("steve");
array.add("john");
array.add("david");

 System.out.println(System.identityHashCode(array)); // Output: 112810359        

Then I change the value of index 1 to be "Steve Loc"

array.set(0, "a1");

System.out.println(System.identityHashCode(array)); // Output: 112810359        

The Output before and after change the value in Object is the same and that is Mutable Object


How to make a Mutable class?

  • Provide setter methods to allow modification of the fields.
  • Fields do not need to be final, and they can be changed after object creation.

Example:

public class MutableExample {
    private int value;

    public MutableExample(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }
}        


The question is, when in the MutableExample have one or more Immutable class like String or others, the MutableExample is still Mutable class or Immutable class?


The answer is: It still Mutable class wherever contain Immutable class

Example:

public class MutableExample {
    private int value;
    private String key; //  String is immutable, but the reference can change

    public MutableExample(int value, String key) {
        this.value = value;
        this.key = key;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }
}        


Advantages:

  • Flexibility: They are flexible and can be modified after creation to accommodate changing requirements.
  • Efficiency: Sometimes, modifying an object is more efficient than creating a new one.

When to use it?

  • Use immutable objects when you need safety from concurrent access, simplicity in design, or when you need objects that won’t change.
  • Use mutable objects when the object’s state needs to be modified after creation, such as in most data structures or domain models that evolve over time.



Thanks for reading <3


Please share your thoughts on the concept of immutable objects in Java in the comments right here 👉

Trần Đông Thạnh

⚡Database Administrator | SQL, Oracle Database ⚡

8mo

Very helpful!

To view or add a comment, sign in

More articles by Steve Loc

  • Understanding and Implementing BRIN Indexes in PostgreSQL

    1. Introduction to BRIN Indexes BRIN (Block Range Index) is a built-in index type in PostgreSQL designed for handling…

  • Best Practices and Pitfalls in Java Exception Handling

    In Java programming, exception handling is essential for creating robust and error-resilient applications. By…

  • Introduce about Table-Level Locks in PostgreSQL

    PostgreSQL employs diverse lock modes to manage concurrent data access in tables, complementing Multi-Version…

  • 4 SQL Phenomena and How to avoid it in Postgresql

    Explanation of Four SQL Phenomena When dealing with concurrent transactions in a relational database, certain issues…

  • PostgreSQL Temporary Table

    Summary: in this tutorial, you will learn about the PostgreSQL temporary table and how to manage it effectively…

    3 Comments
  • Parallel Processing in PostgreSQL: Setup, How It Works, and Use Cases

    PostgreSQL’s parallel processing allows queries to run faster by distributing work across multiple CPU cores. This…

  • Java Collections Interview Questions

    1. List versus Set in Collection framework? List have elements of same type entered in ordered form and allows…

    5 Comments
  • Avoiding Null Checks in Java with Optional

    The NullPointerException (NPE) in Java is one of the most common runtime errors that developers face. It occurs when…

  • Immutable Objects in Java

    In Java, understanding the difference between immutable and mutable objects is key to writing effective code. Immutable…

  • Database Replication

    Database replication can be used in many database management systems, usually with a master/slave relationship between…

    2 Comments

Insights from the community

Others also viewed

Explore topics