Previous Page Next Page Start of Tutorial > Start of Trail > Start of Lesson Lesson Contents

Trail:
Essential Java Classes
Lesson:
The String and StringBuffer Classes



Help on searching
is available.

Search technology
by Excite, Inc.

Creating Strings and StringBuffers

The bold line in the reverseIt method creates a StringBuffer named dest whose initial length is the same as source.
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 code 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(len) initializes the object. These three steps--declaration, instantiation, and initialization--are described in Creating Objects(in the Learning the Java Language trail).

Creating a String

Many Strings are created from string literals. When the compiler encounters a series of characers enclosed in double quotes, it creates a String object whose value is the text that appeared between the quotes. When the compiler encounters the following string literal, it creates a String object whose value is Gobbledy gook.
"Gobbledy gook."
You can also create String objects as you would any other Java object: using the new keyword.
new String("Gobbledy gook.");

Creating a StringBuffer

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.
 
Previous Page Next Page Start of Tutorial > Start of Trail > Start of Lesson Lesson Contents

Michel RIVEILL

Laboratoire I3S - Bât. ESSI
930 Route des Colles
06903 Sophia Antipolis CEDEX

email : riveill at unice.fr

Généralité

Projet Rainbow

Ressources en lignes

Les rubriques des cours :

 

Rechercher sur ce site avec Google

 

dernière mise à jour
le 18 septembre 2003

 

 

Réservation d'Hôtel à Prix Réduits - HotelClub