|
|
The String and StringBuffer Classes |
Strings and StringBuffers
The bold line in thereverseItmethod creates aStringBuffernameddestwhose initial length is the same assource.The codeclass 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(); } }StringBuffer destdeclares to the compiler thatdestwill be used to refer to an object whose type isStringBuffer, thenewoperator allocates memory for a new object, andStringBuffer(len)initializes the object. These three steps--declaration, instantiation, and initialization--are described in Creating Objects.
Creating a
StringManyStrings are created from string literals. When the compiler encounters a series of characers enclosed in double quotes, it creates aStringobject whose value is the text that appeared between the quotes. When the compiler encounters the following string literal, it creates aStringobject whose value isGobbledy gook.You can also create"Gobbledy gook."Stringobjects as you would any other Java object: using thenewkeyword.new String("Gobbledy gook.");Creating a
StringBufferThe constructor method used byreverseItto initialize thedestrequires an integer argument indicating the initial size of the newStringBuffer.StringBuffer(int length)reverseItcould have usedStringBuffer'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.
|
|
The String and StringBuffer Classes |