Topics Index

Strings > StringBuffer >
Siva Nookala - 14 Apr 2016
The StringBuffer class is a thread-safe, mutable sequence of characters. Following are the important points about StringBuffer:
  • A StringBuffer is like a String, but can be modified.
  • It contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.
  • They are safe for use by multiple threads.
  • Every StringBuffer has a capacity.

StringBuffer()Constructs a string buffer with no characters in it and an initial capacity of 16 characters.
StringBuffer(CharSequence seq)Constructs a string buffer that contains the same characters as the specified CharSequence.
StringBuffer(int capacity)Constructs a string buffer with no characters in it and the specified initial capacity.
StringBuffer(String str)Constructs a string buffer initialized to the contents of the specified string.

class StringBufferConstructorDemo
    public static void main(String arg[])
        StringBuffer sb1 = new StringBuffer();
        System.out.println("Empty StringBuffer : " + sb1);
        CharSequence cs = "ABC"; // LINE A
        StringBuffer sb2 = new StringBuffer(cs);
        System.out.println("StringBuffer using CharSequence : " + sb2);
        String s = "XYZ"; // LINE B
        StringBuffer sb3 = new StringBuffer(s);
        System.out.println("StringBuffer using String : " + sb3);    

Empty StringBuffer :
StringBuffer using CharSequence : ABC
StringBuffer using String : XYZ


An empty StringBuffer is created at first. Next a StringBuffer is created using a CharSequence and finally a StringBuffer is created using a String.

  • Include the below code below LINE A
    CharSequence sequence = "ABC";
    The output will be true, since both references contain the same value.
  • Include the below line of code at LINE A.
    The output will be false even though both the references have the same value because there are references of two different types of objects.

Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.