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 the Length of a String, String Buffer, or String Builder

Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings, string buffers, and string builders is the length method, which returns the number of characters contained in the object. After the following two lines of code have been executed, len equals 17:
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
In addition to length, the StringBuffer and StringBuilder classes have a method called capacity, which returns the amount of space allocated rather than the amount of space used. For example, the capacity of the string builder referred to by dest in the StringsDemo program never changes, although its length increases by 1 for each iteration of the loop. The following figure shows the capacity and the length of dest after nine characters have been appended to it.

A string buffer's length is the number of characters it contains; a string buffer's capacity is the number of character spaces that have been

A string buffer or string builder's length is the number of characters it contains; its capacity is the number of character spaces that have been allocated.

The String class doesn't have a capacity method, because a string cannot change.


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.