|
|
The String and StringBuffer Classes |
The
toStringMethodIt's often convenient or necessary to convert an object to aStringbecause you need to pass it to a method that accepts onlyStringvalues. For example,System.out.printlndoes not acceptStringBuffers, so you need to convert aStringBufferto aStringbefore you can print it. 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.The valueOf Method
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));
|
|
The String and StringBuffer Classes |