Java/J2EE and SOA (325 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (41 Blogs)
  • Comprehensive Java Course (2 Blogs)
  • Java/J2EE and SOA (324 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-widget-banner-bg

What is the difference between Mutable and Immutable In Java?

Last updated on Nov 26,2019 2.1K Views
5 / 12 Blog from Java Strings

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

Java being one of the most popular object-oriented programming language provides various concepts for creating applications, and one such concept is Mutable And Immutable in Java. Well, this concept relies on making changes to the fields after the object creation and thus eases programming for Java developers. So, in this article on mutable and immutable in Java, I will discuss the following topics:

What is Mutable object?

The objects in which you can change the fields and states after the object is created are known as Mutable objects. Example: java.util.Date, StringBuilder, and etc.

What is Immutable object?

The objects in which you cannot change anything once the object is created are known as Immutable objects. Example: Boxed primitive objects like Integer, Long and etc.

So, now that you know what is mutable and immutable in java, let us move forward and see the differences between the two.

Difference Between Mutable and Immutable objects

You can refer to the following table for the differences between mutable and immutable objects in Java.

MutableImmutable
Fields can be changed after the object creationFields cannot be changed after object creation
Generally provides a method to modify the field valueDoes not have any method to modify the field value
Has Getter and Setter methodsHas only Getter method
Example: StringBuilder, java.util.DateExample: String, Boxed primitive objects like Integer, Long and etc

Now that you know the differences between mutable and immutable objects, let us look into how to create these  classes.

How to create a Mutable class?

To create a mutable class in Java you have to make sure the following requirements are satisfied:

  1. Provide a method to modify the field values
  2. Getter and Setter method

Consider the following code:


package edureka;

public class example {
private String coursename;
example(String coursename) {
this.coursename = coursename;
}
public String getName() {
return coursename;
}
public void setName(String coursename) {
this.coursename = coursename;
}
public static void main(String[] args) {
example obj = new example("Machine Learning");
System.out.println(obj.getName());

// update the name, this object is mutable
obj.setName("Machine Learning Masters");
System.out.println(obj.getName());

}
}

You would see the following output:

Mutable Object Output - Mutable and Immutable in Java- Edureka

So now that you know how to create a mutable class, next in this article, let us look into how to create an immutable class.

How to create an Immutable class?

To create an immutable class in Java you have to make sure the following requirements are satisfied:

  1. A class should be declared as final so that it can’t be extended.
  2. All the fields should be made private so that direct access is not allowed
  3. No setter methods
  4. Make all mutable fields final, so that they can be assigned only once.

package edureka;

public class exampleimmutable {
private final String coursename;
exampleimmutable(final String coursename) {
this.coursename = coursename;
}
public final String getName() {
return coursename;
}
public static void main(String[] args) {
example obj = new example("Machine Learning");
System.out.println(obj.getName());

}
}

You would see the below output:

Immutable Object - Mutable and Immutable in Java - EdurekaAlright, so now that you know about mutable and immutable objects, let me tell you that Strings are immutable in Java. Now, I am sure this might have raised a question, on why are strings immutable in Java. So, next in this article, let us look at the same.

Why are Strings Immutable in Java?

Java uses the concepts of string literals. So, if you consider an example where you have many reference variables referring a single object, then even if one reference variable changes the value of the object, automatically all the other reference variables will be affected. Also, according to Effective Java, chapter 4, page 73, 2nd edition, the following are reasons to use Immutable classes:

  • Immutable objects are simple
  • These objects require no synchronization and are inherently thread-safe
  • Immutable objects make good building blocks for other objects

If I have to explain you with an example, then,

Let us say you have a variable samplestring, which stores the string “Machine Learning“. Now, if you concatenate this string with another string Masters“, then the object created for “Machine Learning” will not change. Instead, a new object will be created for “Machine Learning Masters“. Refer to the below image:

As you can see in the above image, the samplestring reference variable refers to “Machine Learning”, but not the other string, even after the creation of two objects. With this, we come to an end to this article on Mutable and Immutable in Java. I hope you guys are clear about each and every aspect that I have discussed above.

Now that you have understood basics of Java, check out the Java training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this “Mutable and Immutable in Java” blog and we will get back to you as soon as possible. 

Comments
0 Comments

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.