The String and StringBuffer Classes |
The
toString
MethodIt's often convenient or necessary to convert an object to aString
because you need to pass it to a method that accepts onlyString
values. For example,System.out.println
does not acceptStringBuffer
s, so you need to convert aStringBuffer
to aString
before you can print it. ThereverseIt
method used earlier in this lesson usesStringBuffer
'stoString
method to convert theStringBuffer
to aString
object before returning theString
.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(); } }All classes inherit
toString
from theObject
class and many classes in thejava.lang
package override this method to provide an implementation that is meaningful to that class. For example, the "type wrapper" classes--Character
,Integer
,Boolean
, and the others--all overridetoString
to provide aString
representation of the object.The valueOf Method
As a convenience, theString
class provides the class methodvalueOf
, You can usevalueOf
to convert variables of different types toString
s. For example, to print the value of pi:System.out.println(String.valueOf(Math.PI));
The String and StringBuffer Classes |