The difference between Mutable objects and immutable objects

Anyone please give the difference between Mutable objects and Immutable objects with an example.

+74
java terminology
Jan 11 2018-11-11T00:
source share
5 answers

Mutable objects have fields that can be changed, immutable objects do not have fields that can be changed after the object is created.

A very simple immutable object is an object without any field. (For example, a simple implementation of the Comparator).

class Mutable{ private int value; public Mutable(int value) { this.value = value; } getter and setter for value } class Immutable { private final int value; public Immutable(int value) { this.value = value; } only getter } 
+89
Jan 11 2018-11-11T00:
source share

Mutable objects can change their fields after construction. Immutable objects cannot.

 public class MutableClass { private int value; public MutableClass(int aValue) { value = aValue; } public void setValue(int aValue) { value = aValue; } public getValue() { return value; } } public class ImmutableClass { private final int value; // changed the constructor to say Immutable instead of mutable public ImmutableClass (final int aValue) { //The value is set. Now, and forever. value = aValue; } public final getValue() { return value; } } 
+50
Jan 11 2018-11-11T00:
source share

Immutable objects are simply objects whose state (object data) cannot change after construction. Examples of immutable objects from the JDK include String and Integer.

For example: (dot is mutable and immutable string)

  Point myPoint = new Point( 0, 0 ); System.out.println( myPoint ); myPoint.setLocation( 1.0, 0.0 ); System.out.println( myPoint ); String myString = new String( "old String" ); System.out.println( myString ); myString.replaceAll( "old", "new" ); System.out.println( myString ); 

Output:

 java.awt.Point[0.0, 0.0] java.awt.Point[1.0, 0.0] old String old String 
+27
Jan 11 2018-11-11T00:
source share

Immutable The state of an object cannot be changed.

e.g. String .

 String str= "abc";//a object of string is created str = str + "def";// a new object of string is created and assigned to str 
+19
Jan 11 2018-11-11T00:
source share

They do not differ from the point of view of the JVM. Immutable objects do not have methods that can change instance variables. And instance variables are private; therefore, you cannot change it after creating it. A famous example would be String. You have no methods like setString or setCharAt. And s1 = s1 + "w" will create a new line, and the original will be left. That is my understanding.

+10
Jan 11
source share



All Articles