What is mutable and immutable in java

What you will learn here about mutable and immutable in java

  1. What is immutable in java
  2. What is mutable in java

What is immutable in java

In java Objects are called as immutable object whose states or properties can not be modify or change once it is assigned. For example String is immutable object in java.
what is mutable and immutable in java

public class Immutable
{

	public static void main(String[] args)
	{
	
	//New object is created and reference assign to name variable
	String name="John"; 
	
	//this will not create new object, it will assign reference of "John" to temp variable
	String temp=name; 
	
	//This will create new Object and assign new reference to name
	name="John "+"Dow";
	
	System.out.println(temp);
	
	System.out.println(name);
	}

}

OUTPUT

John

John Dow

What is mutable in java

In java Objects are called as mutable object whose states or properties can be modify or change once it is assigned. For example consider there is a Student class and it has name and age are variable. Once we create an object of Student class we can also change the name and age of particular object using reference of that object.

public class Student {
	
	//instance variables
	String name;
	String lastName;
	int age;
		
	public Student()
	{
	}
	
	//Custom constructor
	public Student(String name,String lastName,int age)
	{
		this.name=name;
		this.lastName=lastName;
		this.age=age;
	}
	
	public static void main(String[] args) 
	{
		//Object is created amd properties are set
		Student obj=new Student("John","Dow",20);
		System.out.println("name : "+obj.name+", Last name : "+obj.lastName+", age : "+obj.age);

		//changing lastname of obj
		obj.lastName="Cena"; //Object properties change means this muttable
		System.out.println("name : "+obj.name+", Last name : "+obj.lastName+", age : "+obj.age);
	}

}

OUTPUT

name : John, Last name : Dow, age : 20
name : John, Last name : Cena, age : 20

You may also like...