what is string builder & why it is used?
What is string builder & why it is used?
String
does not allow appending. Each method you invoke on a String
creates a new object and returns it. This is because String
is immutable - it cannot change its internal state.
On the other hand StringBuilder
is mutable. When you call append(..)
it alters the internal char array, rather than creating a new string object.
Thus it is more efficient to have:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 500; i ++) {
sb.append(i);
}
rather than str += i
, which would create 500 new string objects.
StringBuilder
is much faster and consumes less memory.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.