站内搜索: 请输入搜索关键词
当前页面: 在线文档首页 > Java Tutorial 5.0 英文版

Strings, String Buffers, and String Builders - Java Tutorial 5.0 英文版

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, String Buffers, and String Builders

The Java platform provides three classes String (in the API reference documentation), StringBuffer (in the API reference documentation) and StringBuilder (in the API reference documentation) which store and manipulate strings — character data consisting of more than one character. Use the following guidelines for deciding which class to use:
  • If your text is not going to change, use a string — a String object is immutable.
  • If your text will change, and will only be accessed from a single thread, use a string builder.
  • If your text will change, and will be accessed from multiple threads, use a string buffer.

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.

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.format("%s%n", 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.