Wednesday, May 21, 2008

What are Immutable and Mutable Objects (String vs StringBuffer)

 public static void main(String[] arg) { 
/* String */

String a = "abc";
String b = "def";
String c = "def";

System.out.println(a.hashCode());
a += "xyz";
System.out.println(a.hashCode());
System.out.println(b.hashCode());
System.out.println(c.hashCode());
System.out.println(a);

/* StringBuffer */

StringBuffer sb = new StringBuffer("wer");
System.out.println(sb.hashCode());
sb.append("ert");
System.out.println(sb.hashCode());
}


Output:
-------

96354
-1424366089
99333
99333
abcxyz
17523401
17523401

Explanation:
------------

Mutable and Immutable objects :
The objects whose values can be changed in the same address, are Mutable objects.
The objects whose values cannot be changes in the same address, are Immutable objects.

Example : String and StringBuffer

The main difference, String is Immutable whereas StringBuffer is Mutable.
String is Notsynchronized whereas StringBuffer is Synchronized.
String doesnt have an append method whereas StringBuffer has.


Important Note:
In the code above, when a String "def" is assigned to 'b', it is stored at address "99333".
Again, if I assign the same String "def" to "c", it points to the same address "99333".

No comments: