Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
The Java platform provides two classes,String
andStringBuffer
, that 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 the method. 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. Because strings are constants, they are more efficient to use than are string buffers and can be shared. So it's important to use strings when you can.Following is a sample program called
StringsDemo
, which reverses the characters of a string. This program uses both a string and a string buffer.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(); StringBuffer dest = new StringBuffer(len); for (int i = (len - 1); i >= 0; i--) { dest.append(palindrome.charAt(i)); } System.out.println(dest.toString()); } }In addition to highlighting the differences between strings and string buffers, this section discusses several features of thedoT saw I was toDString
andStringBuffer
classes: creating strings and string buffers, using accessor methods to get information about a string or string buffer, and modifying a string buffer.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2001 Sun Microsystems, Inc. All rights reserved.