public class StringBufferDemo { public static void main(String[] args) { // Creating a StringBuffer object StringBuffer sb = new StringBuffer("Hello"); // 1. append() sb.append(" World"); System.out.println("After append: " + sb); // 2. insert() sb.insert(5, ","); System.out.println("After insert: " + sb); // 3. replace() sb.replace(5, 6, "!"); System.out.println("After replace: " + sb); // 4. delete() sb.delete(5, 6); System.out.println("After delete: " + sb); // 5. deleteCharAt() sb.deleteCharAt(5); System.out.println("After deleteCharAt: " + sb); // 6. reverse() sb.reverse(); System.out.println("After reverse: " + sb); // Reversing back to original for further operations sb.reverse(); // 7. setCharAt() sb.setCharAt(5, '-'); System.out.println("After setCharAt: " + sb); // 8. substring() String subStr = sb.substring(0, 5); System.out.println("Substring (0, 5): " + subStr); // 9. length() int length = sb.length(); System.out.println("Length of StringBuffer: " + length); // 10. capacity() int capacity = sb.capacity(); System.out.println("Capacity of StringBuffer: " + capacity); // Additional methods for better understanding // Ensure Capacity sb.ensureCapacity(50); System.out.println("New Capacity after ensureCapacity(50): " + sb.capacity()); // Trim to Size sb.trimToSize(); System.out.println("Capacity after trimToSize: " + sb.capacity()); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter