Sunday, December 18, 2011

Java's character and assorted string classes support text-processing - 18


Create a StringBuffer object via any of the following constructors:
  • public StringBuffer() creates a new StringBuffer object that contains no characters but can contain up to 16 characters before automatically expanding. StringBuffer has an initial capacity of 16 characters.
  • public StringBuffer(int initCap) creates a new StringBuffer that contains no characters and up to initCap characters before automatically expanding. If initCap is negative, this constructor throws a NegativeArraySizeException object. StringBuffer has an initial capacity of initCap.
  • public StringBuffer(String str) creates a new StringBuffer that contains all characters in the str-referenced String and up to 16 additional characters before automatically expanding. StringBuffer's initial capacity is the length of str's string plus 16.

The following code fragment demonstrates all three constructors:
StringBuffer sb1 = new StringBuffer ();
StringBuffer sb2 = new StringBuffer (100);
StringBuffer sb3 = new StringBuffer ("JavaWorld");

StringBuffer sb1 = new StringBuffer (); creates a StringBuffer with no characters and an initial capacity of 16. StringBuffer sb2 = new StringBuffer (100); creates a StringBuffer with no characters and an initial capacity of 100. Finally, StringBuffer sb3 = new StringBuffer ("JavaWorld"); creates a StringBuffer containing JavaWorld and an initial capacity of 25.

No comments: