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
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 aString
object. Typically, you'll want to useString
s to pass character data into methods and return character data from methods ThereverseIt
method takes aString
argument and returns aString
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 useStringBuffer
s when you know that the value of the character data will change. You typically useStringBuffer
s for constructing character data, as in thereverseIt
method.Because they are constants,
String
s are typically cheaper thanStringBuffer
s and they can be shared. So it's important to useString
s when they're appropriate.
The String and StringBuffer Classes |