0
0
Javaprogramming~15 mins

StringBuilder and StringBuffer in Java - Time & Space Complexity

Choose your learning style8 modes available
scheduleTime Complexity: StringBuilder and StringBuffer
O(n)
menu_bookUnderstanding Time Complexity

We want to understand how fast StringBuilder and StringBuffer work when building strings.

How does the time to add characters grow as the string gets longer?

code_blocksScenario Under Consideration

Analyze the time complexity of the following code snippet.


StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
    sb.append('a');
}
String result = sb.toString();
    

This code builds a string by adding the letter 'a' n times using StringBuilder.

repeatIdentify Repeating Operations
  • Primary operation: The loop runs n times, each time appending one character.
  • How many times: Exactly n times, once per loop iteration.
search_insightsHow Execution Grows With Input

Each append adds one character, so the work grows as the string grows.

Input Size (n)Approx. Operations
10About 10 appends
100About 100 appends
1000About 1000 appends

Pattern observation: The time grows roughly in a straight line as n increases.

cards_stackFinal Time Complexity

Time Complexity: O(n)

This means the time to build the string grows directly with the number of characters added.

chat_errorCommon Mistake

[X] Wrong: "Appending characters takes the same time no matter how long the string is."

[OK] Correct: Sometimes the internal array needs to grow, which takes extra time, but overall it still grows linearly.

business_centerInterview Connect

Understanding how string building scales helps you write efficient code and explain your choices clearly in interviews.

psychology_altSelf-Check

"What if we used String concatenation (+) inside the loop instead of StringBuilder? How would the time complexity change?"