You can't cast explicitly anything to a String
that isn't a String
. You should use either:
"" + myInt;
or:
Integer.toString(myInt);
or:
String.valueOf(myInt);
I prefer the second form, but I think it's personal choice.
Edit OK, here's why I prefer the second form. The first form, when compiled, could instantiate a StringBuffer
(in Java 1.4) or a StringBuilder
in 1.5; one more thing to be garbage collected. The compiler doesn't optimise this as far as I could tell. The second form also has an analogue, Integer.toString(myInt, radix)
that lets you specify whether you want hex, octal, etc. If you want to be consistent in your code (purely aesthetically, I guess) the second form can be used in more places.
Edit 2 I assumed you meant that your integer was an int
and not an Integer
. If it's already an Integer
, just use toString()
on it and be done.
toString()
method that will convert it to a String. As several answers point out, that is what you should use. (For some objects,toString()
doesn't return a very useful string, but forInteger
, it probably does exactly what you want.) – Ted Hopp Jan 23 '12 at 14:53