mam In the 5 point u have told that String Doesn’t have a function to update character at particular position.
But string also have replace function by which we can update our string but as strings are immutable a new string will be created in string pool area with the updated value.
Mam plzz clear this!
Replace function in string
String str = “”;
for(int i=0;i<1000000;i++){
str = str + “abc”;
}
In each iteration of loop, a new string object will be created(since str is immutable and it cant be modified), the old content is copied to new object and new content(“abc”) is appended in this new string object.
so the time complexity actually is x+2x+3x+4x+…, here x is length of content being appended(here 3 for “abc”).
time complexity is x+2x(x for copying old content and x for new content) + 3x(2x old content and x new content)+4x+5x…so on. this is O(n^2).
whereas StringBuffer is mutable, so the complexity for the the same operation with stringbuilder will be linear. the question is, How is mutable property implemented?
StringBuffer is actually implemented using character array and the size of character array is changed as per requirement. when this size changes, at that time only copying occurs. and this size change conditions(you can read about this through web) are in such a way that the amortized cost is linear.