Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › Efficiency & Big-O — Measuring Speed From Zero

Why is building a String in a loop with + considered O(n^2)?

Level II · JuniorEfficiency & Big-O — Measuring Speed From Zero
Short answer

Strings are immutable, so each `s = s + x` inside a loop creates a whole new String by copying all the characters accumulated so far.

Explanation

Copying a growing prefix on every one of n iterations sums to on the order of n^2 character copies. Using a StringBuilder appends into a mutable buffer that grows amortized O(1) per append, making the whole loop O(n). This is a classic example of how data-structure choice changes the complexity class.

Common mistakes
  • Not knowing each + creates a new String and copies the old contents.
  • Thinking the compiler fixes concatenation inside loops.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Efficiency & Big-O — Measuring Speed From Zero.

Practise free

More on Efficiency & Big-O — Measuring Speed From Zero