Java Reference
In-Depth Information
StringBuffer object capacity is 20 and string length is 0
String in StringBuffer object is:
Too many cooks spoil the broth
StringBuffer object capacity is now 42 and string length is 30
String in StringBuffer object is:
Too many cookies spoil the brother
StringBuffer object capacity is now 42 and string length is 34
How It Works
You first create a StringBuffer object with a buffer capacity of 20 characters with the following state-
ment:
StringBuffer sentence = new StringBuffer(20);
The output statement that follows just displays the buffer capacity and the initial string length. You obtain
these by calling the capacity() and length() methods, respectively, for the sentence object. The
string length is zero because you have not specified any buffer contents.
The next four statements create an array of words and append those words to sentence :
String[] words = {"Too" , "many", "cooks", "spoil", "the" ,
"broth"};
sentence.append(words[0]);
for(int i = 1 ; i < words.length ; ++i) {
sentence.append(' ').append(words[i]);
To start the process of building the string, you append the first word from the words array to sentence .
You then append all the subsequent words in the for loop, preceding each word with a space character.
The next output statement displays the buffer contents as a string by calling the toString() method for
sentence to create a String object. You then output the buffer capacity and string length for sentence
once more. The output shows that the capacity has been automatically increased to 42 and the length of
the string is 30.
In the last phase of the program you insert the string "ie" after the substring "cook" with the statement:
sentence.insert(sentence.lastIndexOf("cooks")+4,"ie");
The lastIndexOf() method returns the index position of the last occurrence of "cooks" in sentence ,
so you add 4 to this to specify the insertion position after the last letter of "cook" . You use the same
mechanism to insert the string "er" following "broth" in the buffer.
Finally, you output the string and the capacity and string length with the last two statements in main() :
System.out.println("\nString in StringBuffer object is:\n" +
sentence);
System.out.println("StringBuffer object capacity is now "+
sentence.capacity() +
" and string length is "+sentence.length());
Search WWH ::




Custom Search