The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Object Basics and Simple Data Objects

Strings and String Buffers

Traditionally, the The Java platform has always provided two classes, String, and StringBuffer, which store and manipulate strings- character data consisting of more than one character. The String 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 a String object into it. The StringBuffer 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. The StringBuilder 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:

Following is a sample program called StringsDemo (in a .java source file), 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 of StringBuilder to StringBuffer and the code will compile.

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 output from this program is:
doT saw I was toD
The following sections discuss several features of the String, StringBuffer, and StringBuilder classes.

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.