Mutable and immutable objects in java

Mutable objects

Immutable objects are like variables. We not modify them once they are created. They are not final in nature. Examples: StringBuffer, StringBuilder, java.util.Date etc.

Example

class MutableStudent{
    private String name;
 
	MutableStudent(String name) {
		this.name = name;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
}
 
public class Main {
 
    public static void main(String[] args) {
        MutableStudent mutableStudent = new MutableStudent("Jai");
        System.out.println("Student Name: " + mutableStudent.getName());
        mutableStudent.setName("Sandy");
        System.out.println("Student Name after modification: " + mutableStudent.getName());
    }
}

Output

Student Name: Jai  
Student Name after modification: Sandy

Immutable objects

Immutable objects are like constants. We cannot modify them once they are created. They are final in nature. Examples: String, Wrapper class objects like Integer, Long and etc.

Example

final class ImmutableStudent{
    private String name;
 
	MutableStudent(String name) {
		this.name = name;
	}
 
	public String getName() {
		return name;
	}
 
}
 
public class Main {
 
    public static void main(String[] args) {
        MutableStudent mutableStudent = new MutableStudent("Jai");
        System.out.println("Student Name: " + mutableStudent.getName());
        //mutableStudent.setName("Sandy"); No setter method, so no modification
    }
}

Immutable class in detail

Java interview questions on String Handling