|
|
The String and StringBuffer Classes |
An object's instance variables are encapsulated within the object, hidden inside, safe from inspection or manipulation by other objects. With certain well-defined exceptions, the object's methods are the only means by which other objects can inspect or alter an object's instance variables. Encapsulation of an object's data protects the object from corruption by other objects and conceals an object's implementation details from outsiders. This encapsulation of data behind an object's methods is one of the cornerstones of object-oriented programming.Methods used to obtain information about an object are known as accessor methods. The
reverseItmethod uses two ofString's accessor methods to obtain information about thesourcestring.
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(); } }First,
reverseItusesString'slengthaccessor method to obtain the length of the
Stringsource.Note thatint len = source.length();reverseItdoesn't care ifStringmaintains its length attribute as an integer, as a floating point number, or even ifStringcomputes its length on the fly.reverseItsimply relies on the public interface of thelengthmethod, which returns the length of theStringas an integer. That's allreverseItneeds to know.Second,
reverseItuses thecharAtaccessor, which returns the character at the position specified in the parameter.
The character returned bysource.charAt(i)charAtis then appended to theStringBufferdest. Since the loop variableibegins at the end ofsourceand proceeds backwards over the string, the characters are appended in reverse order to theStringBuffer, thereby reversing the string.More Accessor Methods
In addition tolengthandcharAt,Stringsupports a number of other accessor methods that provide access to substrings and the indices of specific characters in theString.StringBufferhas its own set of similar accessor methods.
|
|
The String and StringBuffer Classes |