Introduction to the append method of stringbuffer objects, in Java 2 getting started classic (JDK 5) by Ivor Horton (English name: Beginning Java 2, JDK 5 edition) section 4th (add other content to the stringbuffer object) describes the append sub-string function using the append () method. The original article provides the following example: stringbuffer Buf = new stringbuffer ("hard"); string astring = "waxworks"; Buf. append (astring, 3, 4); original description: this operation appends a substring consisting of four characters starting from index 3 to the stringbuffer object Buf. Then
The Buf object contains the character string "hard work ".
Note thatCodeThe actual running result is: The Buf object contains the string "hard w ". According to the analysis of running results, the parameter of the append () method of the stringbuffer object. If it is of the string type, the next sub-string operation actually starts from index 3, the string before index 4. If the append statement is changed to Buf. append (astring, 3, 3);, then no astring substring is added, that is, the character contained in the Buf is still "hard ". If this statement is changed to Buf. append (astring3, 2);, the system will throw an "indexoutofboundsexception" exception! However, if the append () parameter is a character array (char []), the result is as described in the original article, and the Buf will contain the string "hard work ". the Code is as follows: stringbuffer Buf = new stringbuffer ("hard ");
Char [] Text = {'w', 'A', 'x', 'w', 'O', 'R', 'k', 's'}; Buf. append (text, 3, 4); // Buf inclusion string "hard work"