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:
As the name suggests insert lets you insert a substring in the StringBuilder object at some specific index provided by you.
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:
Append method on the other hand lets you add a string at the end of StringBuilder object.
|insert() method||append() 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.|