Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › Strings, StringBuilder & String Pool

What's the difference between StringBuilder and StringBuffer, and when does capacity tuning matter?

Level II · JuniorStrings, StringBuilder & String Pool
Answer

They have identical APIs, but StringBuffer's methods are synchronized and StringBuilder's are not, so StringBuilder is the default choice for single-threaded use (almost always) and StringBuffer only when one builder is genuinely shared across threads — which is rare and usually better solved another way. Both grow by reallocating and copying when capacity is exceeded; presizing with new StringBuilder(expectedSize) avoids repeated array copies when you're appending a large, known volume of text in a hot path.

Common mistakes
  • Choosing StringBuffer for single-threaded code.
  • Not pre-sizing StringBuilder for large known output.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Strings, StringBuilder & String Pool.

Practise free

More on Strings, StringBuilder & String Pool