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.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(); } }Methods used to obtain information about an object are known as accessor methods. The
reverseIt()
method uses two of String's accessor methods to obtain information about thesource
string.First,
reverseIt()
uses String'slength()
accessor method to obtain the length of the Stringsource
.Note thatint len = source.length();reverseIt()
doesn't care if String maintains its length attribute as an integer, as a floating point number, or even if String computes its length on the fly.reverseIt()
simply relies on the public interface of thelength()
method which returns the length of the String as an integer. That's allreverseIt()
needs to know.Second,
reverseIt()
uses thecharAt()
accessor, which returns the character at the position specified in the parameter.The character returned bysource.charAt(i)charAt()
is then appended to the StringBufferdest
. Since the loop variablei
begins at the end ofsource
and proceeds backwards over the string, the characters are appended in reverse order to the StringBuffer, thereby reversing the string.More Accessor Methods
In addition tolength()
andcharAt()
, String supports a number of other accessor methods that provide access to substrings and the indices of specific characters in the String. StringBuffer has its own set of similar accessor methods.
The String and StringBuffer Classes |