Sunday, February 26, 2012

Java - object types

Java objects are classified into "Mutable objects" and "Immutable objects".

1. Mutable objects: Mutable objects are those objects whose contents can be modified. i.e.; when an object is created, values can be changed for the instance variables at a later point.
Eg: StringBuffer is a mutable object
Note: Most of the classes defined in Java are mutable objects.

2. Immutable objects: Immutable objects are those objects whose contents can't be modified. i.e.; all of the methods available in the class definition returns the value instead of modifying the same object.
Eg: String class objects are immutable.

public class ObjectTypes
{
 public static void main(String args[])
 {
  String s1 = "Hello";
  System.out.println("s1 hashcode = "+s1.hashCode());
  String s2 = "Hai";
  System.out.println("s2 hashcode = "+s2.hashCode());
  s1 += s2;
  System.out.println("s1 hashcode = "+s1.hashCode());
  System.out.println(s1);
 }
}
Output:
s1 hashcode = 69609650
s2 hashcode = 72304
s1 hashcode = -728048514
HelloHai

The above program creates 3 different string objects. i.e.; when we concatenate s2 with s1, a new string object will be created with the resultant value.

String buffer has various different methods to modify the existing data i.e.; append, insert, delete, reverse. You can refer more details on string buffer here.

0 comments:

Post a Comment