Difference between StringBuilder insert and append method


A note on StringBuilder class:

As you know that Strings in Java are immutable i.e, you cannot modify them. To change some character in string, you have to convert it into a character array then perform operations that you want to and then at last convert the character array back to String.

It can be very troublesome, so instead we use StringBuilder object. It is mutable and similar to StringBuffer class except it's Non-synchronized.

StringBuilder offers many methods for String manipulation like:

  • Appending a string at the end
  • inserting a string at some index
  • replace a substring with another
  • delete a substring
  • reversing the string
  • getting substring, etc,

StringBuilder insert Vs append:

StringBuilder insert vs append method difference

As the name suggests insert lets you insert a substring in the StringBuilder object at some specific index provided by you.

StringBuilder sb = new StringBuilder("middle"); sb.insert(0, "First"); String last = "Last"); sb.insert(11, last); //Final content in sb "FirstmiddleLast"

Its time complexity is O(n) as it involves shifting of string. Say you insert a String "abc" to a stringbuilder object with content "1234", following process take place internally:

  1. Get the length of string to insert (l=3)
  2. Move the content in stringbuilder by length l
  3. Insert the string "abc"

Append method on the other hand lets you add a string at the end of StringBuilder object.

StringBuilder sb = new StringBuilder("First"); sb.append("Middle"); sb.append("Last"); //Final content in sb "FirstMiddleLast"


insert() methodappend() method
insert() method inserts string at specified index position. append() method inserts string at end of string.
Complexity of insert() method at end of string is O(n) Complexity of append() method is O(n)
Use of insert() method is preferred if string is to be inserted anywhere in the string other than end. Use of append() method is preferred if string is to be inserted at end.

Solution Worked 0 UpvotesUpvote


Solution Didn't Worked 0 DownvotesDownvote