Mutable and Immutable in Java
Tags: programming, java, algorithms, computerscience
Published: 2023-04-03 11:25:26


Hello Folks 🖖🏼,

The topic of this article will be about the concept of Mutablity and Immutablity in Java. I will try to answer questions such as **"What does Mutable & Immutable mean?"**, "**What is the logic behind this functionality?**", "**How are Mutable or Immutable classes created?**", "**What are the advantages and disadvantages?**".

Let's dive right in and explore these fascinating concepts together. 🚀

---

## **1. Mutable Classes**
Mutable objects are objects that **can be modified after they are initialized**. In some cases, these types of classes can be preferred over immutable classes due to their flexibility and mutable fields.

Examples of these classes include **StringBuffer**, **StringBuilder**, and the **Date** class found in the Java util package. To further clarify what I mean, let me provide a short code example.

```java
// Initialize variable called myString
StringBuilder myString = new StringBuilder("Hello");

//and manipulate it
myString.append(" Word");
    
System.out.println(myString); // Hello World
```
In fact, those who are not familiar with the topic may be a little surprised. They might say, '***I can already do this in any variable I want, can't I?***' Our friends will be able to grasp the underlying logic more clearly when we delve into the details of the topic and the immutable part 🙂

When a change is made in mutable classes, the change is made on the same field **without creating a new space in memory** (the situation is the opposite in immutables 🙂). In fact, the logic behind mutable classes is that they have a **set()** method that we call a **setter**.

However, **being changeable** is not always a good thing for us, as it can cause some side effects... 

For example, using mutable classes in threaded operations can sometimes cause problems for us. **When two execution threads try to access and change a mutable value at the same time, a situation may arise where one overrides the other**. Therefore, we should be careful when using mutable classes.

We mentioned that there are mutable classes that already come with Java. So how would we create our own if we wanted to?

I'll try to explain this with a short code.

```java
public class MutableClass {

   private int mutableField1;
   private String mutableField2;

   public MutableClass(int fld1, String fld2) {
      this.mutableField1 = fld1;
      this.mutableField2 = fld2;
   }

   public int getMutableField1() {
      return mutableField1;
   }

   public void setMutableField1(int mutableField1) {
      this.mutableField1 = mutableField1;
   }

   public String getMutableField2() {
      return mutableField2;
   }

   public void setMutableField2(String mutableField2) {
      this.mutableField2 = mutableField2;
   }
}
```

In this example, we defined the class fields as mutable. Additionally, we created two setter methods, **setMutableField1()** and **setMutableField2()**, for each field to enable us to change their values. This way, **the fields of this class can be modified as desired after the initial use**.

🌟**In summary**,

- Mutable objects are ones that **can be changed without creating a new object in memory**.
- They have a **setter method** in their class.
- They may cause disadvantages in threaded operations due to **race conditions**.

---

## **2.Immutable**

In fact, in this concept, the opposite of the situations explained above is present. **Once an immutable object is initialized, we cannot change its value**. Examples of these objects include **primitive types**, **Wrapper Classes**, **Legacy classes** [(what!?)](https://www.javatpoint.com/legacy-class-in-java), and the **String** class. As an example, readers can refer to my blog post "[String, StringBuilder, and StringBuffer in Java](https://bayten.dev/posts/string-stringbuilder-and-stringbuffer-in-java/)" where I discussed the implications of being mutable or immutable for these three 
classes.

In immutable classes, unlike mutable classes, only **Getter methods are present**. When a change is desired in these classes, **a new area is created in memory and the manipulated version of the variable is stored in this new area**. This creates **unnecessary memory usage** as a new area is constantly created for each manipulation, making immutable classes slower in terms of performance compared to mutable classes. 

Another difference from mutable classes is that **they are safer in threaded processes since they are immutable and cannot be changed**.

So, what should we do if we want to create an immutable class? Let's take a look:

- We can define the class as **final**.
- We can define the variables that will be used in the class as final and assign their initial values through the **constructor method.** Therefore, since these fields are final and have initial values, they will give an error if they are attempted to be changed.
- We do not use the **Setter** method.

Let's now show all that has been explained in the code. In fact, let's try to make the "**MutableClass**" that we created above immutable now.
```java
public final class ImmutableClass {

   private final int immutableField1;
   private final String immutableField2;

   public ImmutableClass(int fld1, String fld2) {
      this.immutableField1 = fld1;
      this.immutableField2 = fld2;
   }

   public int getImmutableField1() {
      return immutableField1;
   }

   public String getImmutableField2() {
      return immutableField2;
   }
}
```

In the code I wrote above, we declared the fields of the class as **final** and assigned **their initial values in the constructor**, making it immutable. Additionally, since we do not have any **setter methods**, the fields of this class cannot be accessed and assigned any value.

To summarize the whole topic and make a comparative analysis, we can create a table as follows, from start to finish.



| Mutable | Immutable |
| --- | --- |
| We can change the value of mutable objects **after initialization**. | Once an immutable object is initiated; **We can not change its values**. |
| The state can be changed. | The state can not be changed. |
| In mutable objects, **no new objects are formed**. | In immutable objects, **a new object is formed when the value of the object is altered.** |
| It provides **methods to change the object.**| It does **not provide any method to change the object value.** |
| It supports **get() and set() methods** to dela with the object. | It only supports **get()** method to pass the value of the object. |
| Mutable classes are **may or may not be thread-safe.** | Immutable classes **are thread-safe.** |
| The essentials for creating a mutable class are methods for **modifying fields, getters and setters.** | The essentials for creating an immutable class are **final class, private fields, final mutable objects**. |

---

**In conclusion**🌟, 

the use of Mutable and Immutable classes in Java is important for software developers to **improve code quality, minimize errors, and optimize performance**. While the use of Mutable classes can be **advantageous in terms of flexibility and customization, their misuse can lead to program errors**.

The use of Immutable classes is **ideal for writing safe and shareable code, but in some cases, they may be disadvantaged in terms of performance.** By choosing the right class types according to the needs of the application, programmers can improve code quality and create more secure, scalable, and performant applications.
&nbsp;



If you have taken the time to read this far, thank you very much. If you notice any mistakes, please feel free to contact me via email.

Happy coding! 🎉

⭐For the original article -> https://bayten.dev/posts/mutable-and-immutable-in-java/