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

Getting Characters by Index from a String or String Buffer

You can get the character at a particular index within a string, string buffer, or string builder by invoking the charAt accessor method. The index of the first character is 0; the index of the last is length()-1. For example, the following code gets the character at index 9 in a string:
String anotherPalindrome = "Niagara. O roar again!"; 
char aChar = anotherPalindrome.charAt(9);
Indices begin at 0, so the character at index 9 is 'O', as illustrated in the following figure:

Use the charAt method to get a character at a particular index.

Use the charAt method to get a character at a particular index.

The figure also shows that to compute the index of the last character of a string, you have to subtract 1 from the value returned by the length method.

If you want to get more than one character from a string, string buffer, or string builder, you can use the substring method. The substring method has two versions, as shown in the following table:

*The substring Methods in the String, StringBuffer and StringBuilder Classes
Method Description
String substring(int)
String substring(int, int)
Returns a new string that is a substring of this string, string buffer, or string builder.The first integer argument specifies the index of the first character. The second integer argument is the index of the last character -1. The length of the substring is therefore the second int minus the first int. If the second integer is not present, the substring extends to the end of the original string.
* The substring methods were added to the StringBuffer class for Java 2 SDK 1.2.

The following code gets from the Niagara palindrome the substring that extends from index 11 to index 15, which is the word "roar":

String anotherPalindrome = "Niagara. O roar again!"; 
String roar = anotherPalindrome.substring(11, 15); 
Use the substring method to get part of a string, string buffer, or string builder. Remember that indices begin at 0.

Use the substring method to get part of a string, string buffer, or string builder.


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.