|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
toString MethodIt's often convenient or necessary to convert an object to aStringbecause you need to pass it to a method that accepts onlyStringvalues. ThereverseItmethod used earlier in this lesson usesStringBuffer'stoStringmethod to convert theStringBufferto aStringobject 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
toStringfrom theObjectclass and many classes in thejava.langpackage 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 overridetoStringto provide aStringrepresentation of the object.
As a convenience, theStringclass provides the class methodvalueOf, You can usevalueOfto convert variables of different types toStrings. 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-2001 Sun Microsystems, Inc. All rights reserved.