Difference between String and StringBuffer in java

Overview of String:
  1. String is Immutable objects.
  2. Immutable objects cannot be modified once they are created.
  3. Next question that comes to our mind is "If String is immutable than how i change the contents of the object?".
  4. Well, to be precise it’s not the same String object that reflects the changes you do. Internally a new String object is created to do the changes.
Example :
      String myString = "Hello";
      Next, you want append "Guest" to the same String. What do you do?
      myString = myString + " Guest";

When you print the content of myString the output will be "Hello Guest".
Although we made use of the same object(myString), internally a new object was created in the process. 
Here "+" is act concatenation operation in String. 

Example:
      String myStr = "Hello".
      Next, you want append "Guest" to the same String using String's concat() method.
      myStr.concat(" Guest");

When you print content of the object(myStr) the output will be "Hello".
Here not call internal a new object. So, you assign explicitly another String object or same String object.

     String tempStr =  myStr.concat(" Guest");
Now, you print the content of  tempStr the output will be "Hello Guest".

Overview of StringBuffer:
  1. StringBuffer is mutable objects.
  2. Mutable objects can be modified after their creation.
The default behavior of StringBuffer:
  1. StringBuffer maintains a character array internally.
  2. When you create StringBuffer with default constructor StringBuffer() without setting initial length, then the StringBuffer is initialized with 16 characters.
  3. The default capacity of 16 characters.
  4. When the StringBuffer reaches its maximum capacity , it will be increase its size by twice the size plus  (2 * old size) + 2.
Example:
       StringBuffer strBuf = new StringBuffer();
       Next, you want append " to Java" to the same object
       strBuf.append("Welcome");

When you print the content of strBuf the output will be "Welcome to Java".


No comments:

Post a Comment