The JavaTM Tutorial

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form

Trail: Learning the Java Language
Lesson: Object Basics and Simple Data Objects

## Why Two String Classes?

> The Java platform provides two classes, `String` and `StringBuffer`, that store and manipulate strings-character data consisting of more than one character. The `String` class provides for strings whose value will not change. For example, if you write a method that requires string data and the method is not going to modify the string in any way, pass a `String` object into the method. The `StringBuffer` class provides for strings that will be modified; you use string buffers when you know that the value of the character data will change. You typically use string buffers for constructing character data dynamically: for example, when reading text data from a file. Because strings are constants, they are more efficient to use than are string buffers and can be shared. So it's important to use strings when you can.

> Following is a sample program called `StringsDemo`, which reverses the characters of a string. This program uses both a string and a string buffer.

> >     public class StringsDemo {
> >         public static void main(String[] args) {
> >             String palindrome = "Dot saw I was Tod";
> >             int len = palindrome.length();
> >             StringBuffer dest = new StringBuffer(len);

> >             for (int i = (len - 1); i >= 0; i--) {
> >                 dest.append(palindrome.charAt(i));
> >             }
> >             System.out.println(dest.toString());
> >         }
> >     }

> The output from this program is:

> >     doT saw I was toD

> In addition to highlighting the differences between strings and string buffers, this section discusses several features of the `String` and `StringBuffer` classes: creating strings and string buffers, using accessor methods to get information about a string or string buffer, and modifying a string buffer.

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form

Copyright 1995-2001 Sun Microsystems, Inc. All rights reserved.