×

Mutable class in Java

A language for object-oriented programming is Java. Because this is an object-oriented language of programming, all of its mechanisms and methods are based on objects. Java has a concept of mutable and immutable objects. Depending on how they can be iterated, Java objects can either be changeable or immutable.

We will talk about Java's mutable as well as immutable objects in this part. We shall also observe how they differ from one another.

What are Mutable Objects?

Objects that can have their values altered after initialization are referred to as mutable objects. After the item is formed, we can alter its values for things like fields and states. For instance, StringBuilder, StringBuffer, Java.util.Date, etc.

heavily influenced by the language. Even changeable objects are not permitted in some of them.

Depending on the properties you expose on a class's public interface, several major languages have a high degree of default mutability. Making immutable objects is extremely difficult in at least a few popular programming languages, especially dynamic languages.

No new object will be generated when we modify an existing mutable object; instead, the value of an existing entity will change. The classes for these objects offer ways to alter them.

Mutable objects have get() and set() methods, which are known as getters and setters. Thread safety may or may not apply to the Mutable object.

What are Immutable Objects?

Immutable objects are those whose values cannot be altered once they have been initialised. Once an object is formed, nothing can be changed. Primitive objects like int, long, float, and double, all legacy classes, the Wrapper class, the String class, etc. are a few examples.

Immutable simply refers to something that cannot be altered or changed. Immutable objects cannot have their object values or states modified once they have been formed.

For immutable objects, there are no Setters (set () function) but only Getters (get () method).

Let's examine the process for developing classes for changeable and immutable objects.

How to create a Mutable class?

Immutable objects are entities whose initialised states cannot be modified. Depending on the situation, it may be required to create an immutable class. For instance, all primitive

In Java, an immutable class indicates that once a object has been created, its content cannot be changed. All wrapper classes in Java, such as Integer, Boolean, Byte, and Short, as well as the String class, are immutable.

 wrapping classes in Java, including Boolean, Character, Byte, Long, Float, Double, and Short, are immutable. Another immutable class is the string class.

The following two requirements must be met in order to create a changeable class:

  • ways to change the field values
  • The objects' getters and setters

Take into account the following changeable class example:

Mutablec.java

// importing all the requried packages
import java .io.*;


public class Mutablec {  
    private String str;  
    Mutablec (String str) {  
    this.str = str;  
    }  
    public String show () {  
    return str;  
    }  
    public void set (String cname) {  
        // Here, we can change the name.
    this.str = cname;  
    }  
    // main method starts here 
    public static void main (String [] args) { 
        // object creation for the main class 
    Mutablec mc = new Mutablec("Manoj kumar"); 
    // Show method to display the string
    System.out.println(mc.show ());  
// Here, we can use the set method to change the name.
    mc.set("Mamilla Manoj");  
    // Show method to display the string
    System.out.println(mc.show ());  
    }  
    }  

Output:

Manoj kumar
Mamilla Manoj

Using the setName method, we are modifying the name value from the aforementioned example.

How to Make an Immutable Class

For a class to be considered immutable, the following requirements must be met:

  • Final class, which cannot be extended and is marked as such.
  • To prevent direct access to the fields, all fields should be private.
  • Nobody sets
  • All changeable fields ought to be marked as final so that after initialization, they cannot be iterated.

Consider the illustration below:

Exmpl1.java

// importing all the requried packages
import java. io.*;
public class Exmpl1 {  
    private final String str;  
    Exmpl1 (final String str) {  
    this.str = str;  
    }  
    public final String show () {  
    return str;  
    }  
    // main method starts here 
    public static void main (String [] args) {  
    // object creation for the main class 
    Exmpl1 obj = new Exmpl1("Jack");  
    // Show method to display the string
    System.out.println(obj.show());  
    }  
    }  

Output:

Jack                                     

The discussion of changeable vs immutable classes and objects follows. Let's talk about how they differ from one another:

In Java, an immutable class indicates that once an object has been created, its content cannot be changed. All wrapper classes in Java, such as Integer, Boolean, Byte, and Short, as well as the String class, are immutable. We may even design our own immutable class. Read through the immutability's qualities before moving on so that you may implement it with confidence. Here are the prerequisites:

  • In order to prevent the creation of child classes, the class should be designated as final.
  • To prevent direct access, data members of the class should be made private.
  • To prevent value changes after object creation, data members in classes must be marked as final.
  • To prevent data members from being changed by an object reference, a parameterized function Object () { [native code] } should do a deep copy initialization of all the fields.
  • Instead of returning the real object reference, getter methods should execute a deep copy of the object to return a copy.

Difference between Mutable and Immutable Objects

Key distinctions between Java's changeable and immutable objects include the following:

  • Without creating a new object, the changeable objects can be altered to every value or state. In contrast, once an immutable object has been created, it cannot be modified in value or state. With immutable objects, a new object is created each time the state of a object is changed.
  • The ability to modify an object's content is provided by mutable objects. In contrast, immutable entities do not offer a way to modify the values.
  • The setters & getters are supported by the mutable objects. In contrast, only setters, not getters, are supported by immutable objects.
  • Immutable entities are thread-safe by default, whereas mutable objects might or might not be thread-safe.
  • StringBuffer, Java.util.Date, StringBuilder, and so on. are examples of mutable classes. Legacy classes, wrapper classes, the String class, etc. are examples of immutable objects.

Think about the table below:

MutableImmutable
After startup, mutable objects can have their value changed.When an immutable entity is started, its values cannot be changed.
The state is modifiable.There is no way to alter the state.
No new variables are declared in changeable objects.When the value of an immutable object is changed, a new object is created.
It offers ways to modify the object.It does not offer a way to modify an object's value.
The get () & set () methods are offered for interacting with the object.Only the get () function is supported for passing object values.
Thread safety could or might not apply to mutable classes.Thread safety exists for immutable classes.
Getter and setter methods, as well as methods for changing fields, are necessary for developing mutable classes.Final class, hidden fields, and final mutable objects are necessary for making an immutable class.

Why are Strings in Java Immutable?

Due to its widespread usage in Java programmes, the String class in Java is a rather unique one. It is immutable in order to improve security and performance. Let's examine it in greater detail:

Strings in Java employ the literal idea. Consider an object with numerous reference variables. A reference variable's value in such a case would modify the value of the entire entity with all its values.

In addition to the causes listed above, the following factors also contribute to the String's immutability:

Immutable objects are extremely straightforward, require no synchronisation, and are naturally thread-safe. However, since immutable objects are useful as construction blocks for other things, we must take extra care of them.

The String is typically made the final object by developers so that it cannot be changed afterwards.

Conclusion

After talking about changeable and immutable entities in Java, we clearly grasp both types of objects and classes. Additionally, we learned how to develop mutable and immutable classes.

Immutable objects can have their content and state modified after being created, and they might or might not be thread-safe. In contrast, immutable objects are thread-safe by default and cannot have their state or value modified.


Related Topics

How to set timer in Java

In this article, you will be very well equipped with the knowledge to set timer in java. The timer in java can be set by using timer class provided by...

3 minutes read.

Transient variable in Java

In this article, you will be acknowledged about transient variable along with its functions. We would conclude by understanding an example program about it. Transient variable By introducing the transitory keyword, we...

3 minutes read.

Java Get Time in UTC

UTC is the abbreviation for Universal Time Coordinated. Before the beginning of UTC, it is mentioned as the Greenwich Mean Time (GMT) but Now it is mentioned as the universal...

4 minutes read.

Prepared statement in Java

Prepared statement: A prepared statement is a statement that is pre-compiled SQL statement, and it is a sub-interface of a statement. Compared to other statement objects in java, Prepared Statement objects have...

3 minutes read.

Segment Tree in Java

Binary trees can address a variety of issues; however, the Segment Tree is more efficient in terms of time complexity. The segment tree in Java is represented using an array. Native...

4 minutes read.

Java Map Example

In Java, the Map is an interface that is used mainly to denote key and value pairs. The central concept and theme of this mapping in the java collection framework...

4 minutes read.

Object Oriented Programming (OOPs)

Since the dawn of earth, we have kept on evolving. The need for evaluation comes with the aim of improving the existing systems when something inappropriate is found for the...

5 minutes read.

Pattern Programs in Java

Pattern Programs in Java In Java, pattern programs are the most important from the perspective of interviews. The pattern programs improve thinking and coding skills. It also helps us to develop a...

27 minutes read.

Java Double Keyword

In java primitive data types, we have two different types of data types which are Boolean and floating-point data types.In floating data type again we have four types which are...

3 minutes read.

Thread Safety and How to Achieve it in Java

Before diving into the topic, let’s just recap the concept of Multithreading provided by Java where we can create and execute multiple threads of the same object. When these multiple...

5 minutes read.

How to Update Java

As we all know that java can be installed in all operating systems like windows, Linux, macOS. We are available with the java 17 and java 18 versions in the...

3 minutes read.

Java finally

Java finally: There are some statements in a program whose execution is extremely important. For example, closing of a database connection. Statements that do the closing of the database connection...

5 minutes read.

Java ArraylistRemove() Time Complexity

In this tutorial, we will learn about how we can remove time complexity in Java ArrayList. But unless we will not learn what is ArrayList, we don’t understand this process....

7 minutes read.

Switch Case Program in Java

Switch Case Program in Java The switch case program in Java controls which code snippet gets executed on the basis of the value of the expression mentioned in the switch statement....

22 minutes read.

Palindrome Partitioning problem in Java

In this article, you will be acknowledged about partitioning of the palindrome. It can be done in many ways. This article makes sure every method is discussed. Palindrome If a string remains...

6 minutes read.

Prime Number Program in Java

Prime Number Program in Java using for loop A natural number which is greater than 1 and has only two factors the number itself and 1 is called prime number. In...

2 minutes read.

Various operations on the Queue using Stack in Java

The Java Collections Framework's core data structures are the Stack and Queue. They are used to store and retrieve identical data in a presentation sequence. These two linear data structures...

7 minutes read.

Java StringBuffer vs StringBuilder

Java StringBuffer vs StringBuilder StringBuffer The StringBuffer class is used to create mutable string. StringBuffer shows writable and growable character sequences. Java StringBuffer program FileName: StringBufferExample.java // A basic program that demonstrates the working...

2 minutes read.

How to convert list to String in Java

Sometimes, we need to transform a listing of characters into a string. A string is a chain of characters, so we will make a string from an individual array without...

4 minutes read.

Program to Reverse a Number in Java

In order to reverse a number, the digit in the first place must be swapped with the digit in the final position, the second digit with the second-to-last digit, and...

3 minutes read.