566 Strings and Characters Chapter 10 Fig. 10.15 (Web hosting isp)

566 Strings and Characters Chapter 10 Fig. 10.15 StringBufferclass appendmethods (part 2 of 2). Actually, StringBuffers and the append methods are used by the compiler to implement the +and +=operators for concatenating Strings. For example, assuming the following declarations: String string1 = “hello”; String string2 = “BC” int value = 22; the statement String s = string1 + string2 + value; concatenates “hello”, “BC”and 22. The concatenation is performed as follows: new StringBuffer().append( “hello” ).append( “BC” ).append( 22 ).toString(); First, Java creates a StringBuffer, then appends to the StringBufferthe String “hello”, the String”BC”and the integer 22. Next, StringBuffer s toString converts the StringBuffer to a String representation and the result is assigned to Strings. The statement s += “!”; is performed as follows: s = new StringBuffer().append( s ).append( “!” ).toString() First, Java creates a StringBuffer, then appends to the StringBuffer the current contents of s followed by “!”. Next, StringBuffer s toString converts the StringBufferto a Stringrepresentation and the result is assigned to s 10.18 StringBufferInsertion and Deletion Methods Class StringBufferprovides nine overloaded insertmethods to allow various data- type values to be inserted at any position in a StringBuffer. Versions are provided for each of the primitive data types and for character arrays, Strings and Objects. (Remember that method toString produces a String representation of any Object.) Each of the methods takes its second argument, converts it to a Stringand inserts it preceding the index specified by the first argument. The index specified by the first argument must be greater than or equal to 0and less than the length of the StringBuffer; otherwise, a StringIndexOutOfBoundsException is generated. Class String- Bufferalso provides methods delete and deleteCharAt for deleting characters at Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/7/01

Leave a Reply