Home Java Java-tips Data Strings Conversion Converting Anything to String

Ask Questions?

View Latest Questions



Converting Anything to String
Posted on: July 26, 2006 at 12:00 AM
Converting any data to strings is easy.

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 (+): Concatenate anything to a string and it will automatically be converted to string.
  • 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.
  • No conversion required. Some common system methods will take any type and convert it, eg, System.out.println().

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

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.]

Copyleft 2005 Fred Swartz MIT License