🚀 TechFlow Now

← Back to Resources

Java StringBuffer Methods

append(String str)

Adds the specified string to the end.

StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb); // Hello World

insert(int offset, String str)

Inserts the specified string at the given position.

sb.insert(6, "Java ");
System.out.println(sb); // Hello Java World

replace(int start, int end, String str)

Replaces characters from start to end with the given string.

sb.replace(6, 10, "C++");
System.out.println(sb); // Hello C++ World

delete(int start, int end)

Deletes characters from start to end.

sb.delete(6, 9);
System.out.println(sb); // Hello World

reverse()

Reverses the content of the StringBuffer.

sb.reverse();
System.out.println(sb); // dlroW olleH

capacity()

Returns the current capacity of the buffer.

System.out.println(sb.capacity()); // e.g., 27

charAt(int index)

Returns the character at the specified index.

System.out.println(sb.charAt(0)); // d

setCharAt(int index, char ch)

Sets the character at the specified index.

sb.setCharAt(0, 'D');
System.out.println(sb); // DlroW olleH

substring(int start, int end)

Returns a substring from start to end.

System.out.println(sb.substring(0, 5)); // DlroW