The StringBuffer and StringBuilder classes are used when there is a necessity to make a lot of modifications to Strings of characters.
Unlike Strings objects of type StringBuffer and Stringbuilder can be modified
over and over again with out leaving behind a lot of new unused objects.
The StringBuilder class was introduced as of Java 5 and the main difference
between the StringBuffer and StringBuilder is that StringBuilders methods are
not thread safe(not Synchronised).
It is recommended to use StringBuilder whenever possible because it is faster
than StringBuffer. However if thread safety is necessary the best option is
StringBuffer objects.
Here we will learn how to create a string buffer. Here we have used the following StringBuffer Constructors.
StringBuffer() //Default Constructor with 16 characters set StringBuffer(String s) //String to String Buffer StringBuffer(int initialCapacity) //StringBuffer?s with initial Capacity |
Example:
public class StringBuffertest{ public static void main(String[] args) { StringBuffer strBuff1 = new StringBuffer("stringbuffer in java"); StringBuffer strBuff2 = new StringBuffer(60); StringBuffer strBuff3 = new StringBuffer(); System.out.println("strBuff1 : " +strBuff1); System.out.println("strBuff2 capacity : " +strBuff2.capacity()); System.out.println("strBuff3 capacity : " +strBuff3.capacity());}} |