Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Traditionally, the The Java platform has always provided two classes,String
, andStringBuffer
, which store and manipulate strings- character data consisting of more than one character. TheString
class provides for strings whose value will not 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, pass aString
object into it. TheStringBuffer
class provides for strings that will be modified; you use string buffers when you know that the value of the character data will change. You typically use string buffers for constructing character data dynamically: for example, when reading text data from a file. String buffers are safe for use in a multi-threaded environment. TheStringBuilder
class, introduced in JDK 5.0, is a faster, drop-in replacement for string buffers. You use a string builder in the same way as a string buffer, but only if it's going to be accessed by a single thread.Use the following guidelines for deciding which class to use:
- If your text is not going to change, use a string.
- If your text will change, and will only be accessed from a single thread, use a string builder.
- If your text will change, but will be accessed from multiple threads, use a string buffer.
Following is a sample program called
StringsDemo
, which reverses the characters of a string. This program uses both a string and a string builder. If you are using a pre-5.0 JDK, simply change all occurances ofStringBuilder
toStringBuffer
and the code will compile.The output from this program is:public class StringsDemo { public static void main(String[] args) { String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); StringBuilder dest = new StringBuilder(len); for (int i = (len - 1); i >= 0; i--) { dest.append(palindrome.charAt(i)); } System.out.println(dest.toString()); } }The following sections discuss several features of thedoT saw I was toDString
,StringBuffer
, andStringBuilder
classes.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.