This question already has an answer here:
- What is meant by immutable? 17 answers
Any one please give the diff between Mutable objects and Immutable objects with example.
This question already has an answer here:
Any one please give the diff between Mutable objects and Immutable objects with example.
Immutable objects are simply objects whose state (the object's data) cannot change after construction. Examples of immutable objects from the JDK include String and Integer.
For example:(Point is mutable and string immutable)
The output is:
Mutable objects have fields that can be changed, immutable objects have no fields that can be changed after the object is created.
A very simple immutable object is a object without any field. (For example a simple Comparator Implementation).
Mutable objects can have their fields changed after construction. Immutable objects cannot.
They are not different from the point of view of JVM. Immutable objects don't have methods that can change the instance variables. And the instance variables are private; therefore you can't change it after you create it. A famous example would be String. You don't have methods like setString, or setCharAt. And s1 = s1 + "w" will create a new string, with the original one abandoned. That's my understanding.
Immutable Object's state cannot be altered.
for example
String
.