For a simple string concantenation code shown below it will create 3 copies of string in memory.
//The below line of code Creates one copy of the string
string str = “shiv”;
/* The below line of code creates three copies of string object one for the concatenation at right hand side and the other for new value at the left hand side. The first old allocated memory is sent for garbage collection.*/
str = str + “shiv”;
When you use the string builder for concatenation it will create only one copy of the object.
/* The below code uses string builder and only one
object is created as compared to normal string where we have 3 copies created*/
StringBuilder objBuilder = new StringBuilder();
Ok now summarizing what should we say to the interviewer.
String is immutable. Immutable means once assigned it can not be changed. Thats why it creates more copies of the object as it can not use the same instance.String builder is mutable , in other words the same object will changed rather than creating new objects.