Course contentsShow
← Java
Lesson 2189 of 2,87043. String Handling in DepthFree lesson

Common StringBuilder Methods: append and insert

Using append for adding content and insert for placing content at specific positions in the sequence.

Common StringBuilder Methods: append and insert

You'll learn how to efficiently add content to a StringBuilder using append and insert.

Now that you understand why StringBuilder exists, it's time to master the two most essential methods for building strings dynamically: append and insert.

The append Method

The append method adds content to the end of the current sequence. Think of it like writing in a notebook—you always continue from where you left off.

StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");  // "Hello World"
sb.append("!");       // "Hello World!"
sb.append(2024);      // "Hello World!2024"

append is overloaded to accept many types: String, char, int, long, boolean, char[], and more. It converts each argument to its string representation and adds it to the end.

The insert Method

The insert method places content at a specific index within the sequence. It's like using correction tape to add words in the middle of a sentence—existing content shifts right to make room.

StringBuilder sb = new StringBuilder("Hello!");
sb.insert(5, " World");  // "Hello World!"
//         index 5 (after 'o')

sb.insert(0, "Say: ");   // "Say: Hello World!"
//         index 0 (beginning)

The first parameter is the insertion point (zero-based index), and the second is the content to insert. Like append, insert is overloaded for various types.

Practical Usage

StringBuilder path = new StringBuilder("/home");
path.append("/user");
path.append("/documents");
path.insert(0, "file://");  // "file:///home/user/documents"

Key Takeaway: Use append to efficiently add content to the end of a StringBuilder, and insert to place content at any specific position—both methods modify the existing instance and return a reference to it, enabling method chaining.