Tricky Tricks ›› Programming Tricks ›› Java Tricks ›› Convert X To A String

Convert X To A String

Java Programming Tricks

Use ""+x to convert x to a string:

 The base class Object has a method toString that subclasses redefine 
 to print out a representation of 
 
 the object. If x is any object, then 
 
 x.toString() 
 
 converts it to a string. 
 
 If x is a number, then you can't call x. toString (), because numbers 
 aren't objects in Java, and you can't 
 
 apply methods. Instead, you are supposed to use 
 
 String.valueOf(x)
 
 Tip 
 
 Just concatenate with an empty string: 
 
 "" + x 
 
 This converts x to a string. If x is a number, then its value is turned 
 into a string. If x is an object, then its toString method is invoked. 
 
 There is no penalty. The Java compiler is aware of this idiom, and it 
 does not generate code to concatenate an empty string.
 

Partners