The JavaTM Tutorial

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

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

## Why Two String Classes?

> The Java development environment provides two classes that store and manipulate character data: `String`, for constant strings, and `StringBuffer`, for strings that can change.

> You use `String`s when you don't want the value of the string to 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, use a `String` object. Typically, you'll want to use `String`s to pass character data into methods and return character data from methods The `reverseIt` method takes a `String` argument and returns a `String` value.

> >     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 `StringBuffer` class provides for strings that will be modified; you use `StringBuffer`s when you know that the value of the character data will change. You typically use `StringBuffer`s for constructing character data, as in the `reverseIt` method.

> Because they are constants, `String`s are typically cheaper than `StringBuffer`s and they can be shared. So it's important to use `String`s when they're appropriate.

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