The JavaTM Tutorial

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form

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

## Strings

> The `java.lang` package contains two string classes: String and StringBuffer. You've already seen the `String` class on several occasions in this tutorial. You use the `String` class when you are working with strings that cannot change. `StringBuffer`, on the other hand, is used when you want to manipulate the contents of the string on the fly.

> The `reverseIt` method in the following code uses both the `String` and `StringBuffer` classes to reverse the characters of a string. If you have a list of words, you can use this method in conjunction with a sort program to create a list of rhyming words (a list of words sorted by ending syllables). Just reverse all the strings in the list, sort the list, and reverse the strings again. You can see the `reverseIt` method producing rhyming words in the example in How to Use Pipe Streams that shows you how to use piped streams.

> >     public 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 `reverseIt` method accepts an argument of type `String` called `source` that contains the string data to be reversed. The method creates a `StringBuffer`, `dest`, the same size as `source`. It then loops backwards over all the characters in `source` and appends them to `dest`, thereby reversing the string. Finally, the method converts `dest`, a `StringBuffer`, to a `String`.

> In addition to highlighting the differences between `String`s and `StringBuffer`s, this section illustrates several features of the `String` and `StringBuffer` classes: creating `String`s and `StringBuffer`s, using accessor methods to get information about a `String` or `StringBuffer`, modifying a `StringBuffer`, and converting one type of string to another.

> > Note to C and C++ Programmers: Java strings are first-class objects, unlike C and C++ strings, which are simply null-terminated arrays of 8-bit characters.

> This section covers these string-related topics:
> - Why Two String Classes?
> - Creating Strings and StringBuffers
> - Accessor Methods
> - Modifying StringBuffers
> - Converting Objects to Strings
> - Converting Strings to Numbers
> - Strings and the Java Compiler

| Start of Tutorial > Start of Trail > Start of Lesson | Search Feedback Form