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.
There are many specialized issues with regard to converting numbers (precision, exponents, currency, locale, ...), which are covered in Converting Numbers to Strings.
toString()
is universally used as the method for converting
any object into a string.printf()
was added in Java 5 to use a format for conversion.
Altho it's primarily used with numbers, it also can be applied to objects
of other classes. This isn't discussed here.System.out.println()
.
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.
When Java needs to convert an object to a String, it calls the
object's toString()
method. Because every class (object type)
has the class Object
as an ancestor, every class
inherits Object's toString()
method.
This will do something to generate 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.]