Skip to main content Skip to docs navigation
TechSpiderTutorials

The StringBuffer Class in Java

On this page

Java History

A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.

Java Versions

import java.io.*;
import java.lang.*;

public class StringBufferDemo
 {
  public static void main(String args[])
   {
  StringBuffer stb=new StringBuffer("Welcome to java");
	
	System.out.println("capacity is..>"+stb.capacity());	
	System.out.println("length is..."+stb.length());	
    System.out.println("Append string is.."+stb.append("-programming"));
	System.out.println("capacity after append is..>"+stb.capacity());		
	System.out.println("length  after append is..."+stb.length());
	
   	StringBuffer newstr=stb.insert(11,"sun-");
    System.out.println("string after insert is.."+newstr);
    System.out.println("deleted string .."+stb.delete(11,15));
    System.out.println("Reverse is..."+stb.reverse());
    stb.trimToSize();
    System.out.println("capacity is..>"+stb.capacity());
	System.out.println("length is..."+stb.length());
    }
}