Java: Converting Anything to String

Summary: Converting any data to strings is easy. You can do almost everything with concatenation, but can get more control using some of the alternatives.

Converting numbers to strings - See Converting Numbers to Strings

There are many specialized issues with regard to converting numbers (precision, exponents, currency, locale, ...), which are covered in Converting Numbers to Strings.

Summary of conversion alternatives

Concatenation (+)

The most common idiom to convert something to a string is to concatenate it with a string. If you just want the value with no additional text, concatenate it with the empty string, one with no characters in it ("").

If either operand of a concatenation is a string, the other operand is converted to string, regardless of whether it is a primitive or object type.

Card c = ...;   // Assume Card is a class that defines a playing card.
String s;
. . .
s = c;             // ILLEGAL
s = "" + c;        // Might assign "Three of Hearts" to s
s = c + " is trouble";  // Assigns "Three of Hearts is trouble" to s.

This conversion to string is made by calling the object's toString() method.

toString() method - Define it for your classes

Method toString is already defined. When Java needs to convert an object to a String, it calls the object's toString() method. Because every class (object type) inherits from the Object class, Object's toString() method is automatically defined. This generates a string from an object, but it will not always be very useful. If the child class doesn't override toString(), the default probably won't print anything interesting. Just as many of the Java library classes override toString() to produce something more useful, you should also override toString() in your classes.


[There should be something here about Java 5's enums.]