Previous | Next | Trail Map | Writing Java Programs | The String and StringBuffer Classes


Creating Strings and StringBuffers

class 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();
    }
}
The reverseIt method above creates a StringBuffer named dest whose initial length is the same as source. StringBuffer dest declares to the compiler that dest will be used to refer to an object whose type is StringBuffer, the new operator allocates memory for a new object, and StringBuffer() initializes the object. These three steps--declaration, instantiation, and initialization--are described in Creating Objects(in the Writing Java Programs trail).

Constructor Methods

The constructor method used by reverseIt to initialize the dest requires an integer argument indicating the initial size of the new StringBuffer.
StringBuffer(int length)
reverseIt could 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


Previous | Next | Trail Map | Writing Java Programs | The String and StringBuffer Classes