java

Mutable and Immutable in Java

In this tutorial, we are going to see the difference between Mutable and Immutable objects in Java.
 

Example of mutable objects:

Mutable objects: You can edit states and fields after creating the object.

public class Person {

	private String name;

	Person(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public static void main(String[] args) 
	{
		Person obj = new Person("Alex");
		System.out.println(obj.getName());

		// Change the name
		obj.setName("Thomas");   // this object is mutable
		System.out.println(obj.getName());

	}
}

Output:

Alex
Thomas
 

Example of immutable objects:

Immutable objects: You cannot change states and fields after creating the object.

public final class Person {

	private String name;

	Person (String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}
	
	public static void main(String[] args) 
	{
		Person obj = new Person("Alex");
		System.out.println(obj.getName());

		// You cannot change the name after creating the object.
	}
}

Output:

Alex
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *