Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
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. 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.
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));
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2002 Sun Microsystems, Inc. All rights reserved.