Previous Page Next Page Start of Tutorial > Start of Trail > Start of Lesson Lesson Contents

Trail:
Essential Java Classes
Lesson:
The String and StringBuffer Classes



Help on searching
is available.

Search technology
by Excite, Inc.

Converting Objects to Strings

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 accepts only 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 used earlier in this lesson uses StringBuffer's toString method to convert the StringBuffer to a String object before returning the String.
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 the Object class and many classes in the java.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 override toString to provide a String representation of the object.

The valueOf Method

As a convenience, the String class provides the class method valueOf, You can use valueOf to convert variables of different types to Strings. For example, to print the value of pi:
System.out.println(String.valueOf(Math.PI));
 
Previous Page Next Page Start of Tutorial > Start of Trail > Start of Lesson Lesson Contents

Michel RIVEILL

Laboratoire I3S - Bât. ESSI
930 Route des Colles
06903 Sophia Antipolis CEDEX

email : riveill at unice.fr

Généralité

Projet Rainbow

Ressources en lignes

Les rubriques des cours :

 

Rechercher sur ce site avec Google

 

dernière mise à jour
le 18 septembre 2003

 

 

Réservation d'Hôtel à Prix Réduits - HotelClub