Previous | Next | Trail Map | Writing Java Programs | The String and StringBuffer Classes


Converting Objects to Strings

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();
    }
}

The toString() Method

It's often convenient or necessary to convert an object to a String because you need to pass it to a method that only accepts String values. For example, System.out.println() does not accept StringBuffers, so you need to convert a StringBuffer to a String before you can print it. The reverseIt() method above uses StringBuffer's toString() method to convert the StringBuffer to a String object before returning the String.
return dest.toString();
Several classes in the java.lang also support toString() including all of the "type wrapper" classes such as Character, Integer, Boolean and the others. Also, the base Object class has a toString() method that converts an Object to a String. When you write a subclass of Object, you can override toString() to perform a more specific conversion for your subclass.

The valueOf() Method

As a convenience, the String class provides the static method valueOf() which you can use to convert variables of different types to Strings. For example, to print the value of pi
System.out.println(String.valueOf(Math.PI));


Previous | Next | Trail Map | Writing Java Programs | The String and StringBuffer Classes