Answer: Strings are immutable means every-time memory is allocated in the Heap.Each time string creates new string in the memory.
But StringBuilder is mutable object.It does not create new string in the memory rather than update the data in the same memory in the heap.
In short,in case of String every-time new string values are added in the memory and discarded the old value.
But in case of StringBuilder,every-time string is added into existing string.
For Example: String:-
string str = "Rajesh Kumar";
str = str + " Sathua";
//In above code,Rajesh Kumar will be discarded in the memory and new value Rajesh Kumar Sathua will be allocated to Heap.
StringBuilder:-
StringBuilder sb = new StringBuilder();
sb.Append("Rajesh Kumar");
sb.Append(" Sathua");
//In above code,Rajesh Kumar will be allocated in the memory and new value Sathua will be appended to Rajesh Kumar and Rajesh Kumar Sathua will be added in Existing Memory.
Asked In: Many Interviews |
Alert Moderator