Previous | Next | Trail Map | Essential Java Classes | The String and StringBuffer Classes


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 Strings 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 Strings 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 StringBuffers when you know that the value of the character data will change. You typically use StringBuffers for constructing character data, as 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 | Essential Java Classes | The String and StringBuffer Classes