J. E. N. I.
Program di bawah ini menunjukkan bagaimana menggunakan method-method tersebut.
class StringBufferDemo { public static void main( String args []) { StringBuffer sb = new StringBuffer(" Jonathan "); System. out. println(" sb = " + sb); /* initial capacity is 16 */ System. out. println(" capacity of sb: " + sb. capacity()); System. out. println(" append \' O \' to sb: " + sb. append(" O "));
System. out. println(" sb = " + sb); System. out. println(" 3 rd character of sb: " + sb. charAt( 2)); char charArr [] = " Hi XX ". toCharArray(); /* Need to add 1 to the endSrc index of getChars */ sb. getChars( 0, 2, charArr, 3); System. out. print(" getChars method: "); System. out. println( charArr); System. out. println(" Insert \' jo \' at the 3rd cell: " + sb. insert( 2, " jo ")); System. out. println(" Delete \' jo \' at the 3rd cell: " + sb. delete( 2,4)); System. out. println(" length of sb: " + sb. length()); System. out. println(" replace: " + sb. replace( 3, 9, " Ong ")); /* Need to add 1 to the endIndex parameter of substring */ System. out. println(" substring( 1st two characters): " + sb. substring( 0, 3)); System. out. println(" implicit toString(): " + sb);
}
}
Ini adalah output dari program yang telah dibuat di atas. Sekali lagi, bereksperimen secara bebas dengan code-code merupakan cara terbaik mempelajari sintaks-sintaks yang ada. sb = Jonathan capacity of sb: 24 append ' O ' to sb: JonathanO sb = JonathanO 3rd character of sb: n getChars method: Hi Jo Insert ' jo ' at the 3rd cell: JojonathanO Delete ' jo ' at the 3rd cell: JonathanO length of sb: 9 replace: Jon Ong substring( 1st two characters): Jon implicit toString(): Jon Ong
Pengenalan Pemrograman 2 8