Pages

Tuesday 3 July 2012

Immutable vs Mutable Objects in Java - the question answer approach



  1. What is an immutable object ? 
An object is considered immutable if its state cannot change after it is constructed. 


     2.  What is happenning to immutable object myString in the example below ? 

	String myString = new String( "old String" );
	String myCache = myString;
	System.out.println( "equal: " + myString.equals( myCache ) );
	System.out.println( "same:  " + ( myString == myCache ) );

	myString = "not " + myString;
	System.out.println( "equal: " + myString.equals( myCache ) );
	System.out.println( "same:  " + ( myString == myCache ) );
Result : 
        equal: true
	same:  true
	equal: false
	same:  false
The contents of myString is not changing here. We are discarding the instance and changed our reference to a new one with new contents. 

     3.  How can you change the values of a variable ? 
  • You can always change the value of a variable by getting your variable to reference a new object. 
  • Sometimes you can change the value of a variable by keeping a reference to the same instance, but change the contents of the instance.
    4.  What are the uses of immutable objects ?

  • They can promote thread safety in your code 
  • You can share them around without being afraid that they will change without your knowledge 
  • They are great for caching and constants
    5.  How can we create a mutable class ? 
  • Make all fields private
  • Don't provide mutators
  • Ensure that methods can't be overridden by either making the class final (Strong Immutability) or making your methods final (Weak Immutability)
  • If a field isn't primitive or immutable, make a deep clone on the way in and the way out.
References : 

No comments:

Post a Comment