|
|
The String and StringBuffer Classes |
Theclass ReverseString { public static String reverseIt(String source) { int i, len = source.length(); StringBuffer dest = new StringBuffer(len); for (i = (len - 1); i >= 0; i--) { dest.append(source.charAt(i)); } return dest.toString(); } }reverseItmethod above creates a StringBuffer nameddestwhose initial length is the same assource.StringBuffer destdeclares to the compiler thatdestwill be used to refer to an object whose type is String, thenewoperator allocates memory for a new object, andStringBuffer()initializes the object. When you create any object in a Java program, you always use the same three steps: declaration, instantiation, initialization. For more information, see Declaring, Instantiating and Initializing an Object.
Constructor Methods
The constructor method used byreverseItto initialize thedestrequires an integer argument indicating the initial size of the new StringBuffer.StringBuffer(int length)reverseItcould have used StringBuffer's default constructor that leaves the buffer's length undetermined until a later time. However, it's more efficient to specify the length of the buffer if you know it, instead of allocating more memory every time you append a character to the buffer.See Also
java.lang.String--Constructors
java.lang.StringBuffer--Constructors
|
|
The String and StringBuffer Classes |