×

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

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

Hidden classes in Java

There specifically are some APIs available in the market that generally is harmful to be used in our programs specifically literally, and until JDK 15, there, for all intents and...

4 minutes read.

How to Create an API in Java?

Introduction The API can be abbreviated as Application Programming Interface. An API is a combination of set of classes and interfaces. It is also equivalent to a simple java program. To...

12 minutes read.

Spliterator in Java 8

In this tutorial, we will understand the meaning of spliterator in java 8. It is just like any other iterator available in java used to traverse the elements of either...

4 minutes read.

Bouncy Number in Java

We will define bouncy numbers in this section and write Java programmes to determine whether a specific number is bouncy. Java coding exams and academic assignments usually inquire about the...

3 minutes read.

Java Iterator

When iterating through, traversing, or retrieving the individual elements of a Collection or Flow object, a Java Cursor is leveraged as an iterator. In Java, there exist three types of...

4 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 minutes read.

Java Math with Methods and Examples

Java Math class contains various methods for performing math operations like min(), max(), avg() and various trigonometric functions like sin(), cos(), tan() etc. Methods: The java.lang.Math class contains various methods for performing...

5 minutes read.

How to create an array in Java

An array is a linear data structure stores a collection of fixed number ofelements of similar type. The size of an array is specified when it is created. The array...

14 minutes read.

Bedrock vs Java

The popularity of Minecraft, a sandbox video game, has skyrocketed. The scope, level of complexity, and variety of gameplay in this game are enormous, and user-generated content has helped to...

4 minutes read.

Java Arrays

An array is an object that stores a collection of values. An array can store two types of collection data: objects and primitives. An array is a collection of values which...

2 minutes read.

Java Substring

What is a substring in Java? Here by the name  " substring " itself, we can easily come to know it is a part of a string or a subset of...

4 minutes read.

Difference Between Data Hiding and Abstraction in Java

Abstraction: Data Abstraction and Data Hiding ideas are utilised to show the expected data to the end client and conceal the superfluous subtleties, however, for specific purposes like decreasing the framework's...

10 minutes read.

Java String Inbuilt functions

There are different types of inbuilt functions available in the Java String class, all of them are listed below. Char chat At (int index)It outputs the character indicated by the index....

5 minutes read.

Balanced Parentheses in Java

One of the frequent programming issues, commonly referred to as the Balanced brackets issue, is the problem with the balanced parenthesis. Interviewers frequently provide this task, in which we must...

5 minutes read.

How to run Java Program in Command Prompt

How to run Java Program in Command Prompt In this section, we will learn how to write, save, compile, and execute or run a Java program in the Command Prompt. Note: One...

3 minutes read.

Java Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates. HashSet: This class stores its elements in hash tables. It uses the hashCode()...

3 minutes read.

Minimum Number of Platforms Required for a Railway Station

The train station problem is one of the most significant problems typically posed in the programming round interview to gauge a candidate's aptitude for logic and problem-solving. Problem of Railway Station The...

6 minutes read.

Thread Program in Java

Thread Program in Java Thread program in Java is the continuation of multithreading program in Java. In this topic, we will learn about the usage of threads, race condition in multithreading,...

8 minutes read.

Access modifiers in Java

Access modifiers in Java with Example In Java, there are two types of access modifiers one is a non-access modifier, and other is access modifier. If we talk about access modifier, there...

3 minutes read.