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


Why Two String Classes?

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 Java development environment provides two classes that store and manipulate character data: String, for immutable strings, and StringBuffer, for mutable strings.

The String class provides for constant strings; you use Strings when you don't want the value of the string to change. For example, if you pass a string data into a method, and you don't want the method to modify the string in any way (which is typical), you would use a String. Typically, you'll want to use Strings to pass character data to methods and return character data from methods. The reverseIt() method takes a String argument and returns a String value.

The StringBuffer class provides for non-constant strings; you use StringBuffers when you know that the value of the character data will change. You typically use StringBuffers for constructing character data like in the reverseIt() method.

Because they are constants, Strings are typically cheaper than StringBuffers and they can be shared. So it's important to use Strings when they're appropriate.


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