Overview of String:
- String is Immutable objects.
- Immutable objects cannot be modified once they are created.
- Next question that comes to our mind is "If String is immutable than how i change the contents of the object?".
- 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.
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:
- StringBuffer is mutable objects.
- Mutable objects can be modified after their creation.
- StringBuffer maintains a character array internally.
- When you create StringBuffer with default constructor StringBuffer() without setting initial length, then the StringBuffer is initialized with 16 characters.
- The default capacity of 16 characters.
- When the StringBuffer reaches its maximum capacity , it will be increase its size by twice the size plus (2 * old size) + 2.
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