Mutable-vs-Immutable types, Reference/Shallow/Deep Copies of Arrays Practice Problems


  1. Write a main method which does the following and then consider the output and how this is a result of aliasing and how String is immutable and StringBuffer is mutable. It creates:
       - a String reference strOne that refers to a String that contains "Hello"
       - a String reference strTwo that refers to the same object as strOne refers to
       - a StringBuffer reference sbOne that refers to a StringBuffer that contains "Hello"
       - a StringBuffer reference sbTwo that refers to the same object as sbOne refers to
    
    then
       - uses the += operator to append "There" to strOne
       - uses the append method to append "There" to sbOne
       - prints strOne, strTwo, sbOne, sbTwo

  2. Write a method that takes a reference to an array of StringBuffer objects as a parameter and returns a reference copy of that parameter array.

  3. Write a method that takes a reference to an array of StringBuffer objects as a parameter and returns a shallow copy of that parameter array.

  4. Write a method that takes a reference to an array of StringBuffer objects as a parameter and returns a deep copy of that parameter array. Note that not every position of the array will refer to a StringBuffer object, some might be null.

  5. Write a main method that will create an array of references to two StringBuffer objects and use it to confirm that your solution to the previous problem actually works.

  6. Is there ever a reason to make a deep copy of an array of references to immutable objects?

  7. How do you make sure that a datatype you are creating is immutable?