|
|
The String and StringBuffer Classes |
The Java development environment provides two classes that store and manipulate character data:String, for constant strings, andStringBuffer, 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 aStringobject. Typically, you'll want to useStrings to pass character data into methods and return character data from methods ThereverseItmethod takes aStringargument and returns aStringvalue.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
StringBufferclass provides for strings that will be modified; you useStringBuffers when you know that the value of the character data will change. You typically useStringBuffers for constructing character data, as in thereverseItmethod.Because they are constants,
Strings are typically cheaper thanStringBuffers and they can be shared. So it's important to useStrings when they're appropriate.
|
|
The String and StringBuffer Classes |