I found some strange exception:
java.lang.ClassCastException: java.lang.Integer
cannot be cast to java.lang.String
How it can be possible
Use String.valueOf(integer).
It returns a string representation of integer.
Casting is different than converting in Java, to use informal terminology.
Casting an object means that object already is what you're casting it to, and you're just telling the compiler about it. For instance, if I have a Foo
reference that I know is a FooSubclass
instance, then (FooSubclass)Foo
tells the compiler, "don't change the instance, just know that it's actually a FooSubclass
.
On the other hand, an Integer
is not a String
, although (as you point out) there are methods for getting a String
that represents an Integer
. Since no no instance of Integer
can ever be a String
, you can't cast Integer
to String
.
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.
For int
types use:
int myInteger = 1;
String myString = Integer.toString(myInteger);
For Integer
types use:
Integer myIntegerObject = new Integer(1);
String myString = myIntegerObject.toString();
No. Every object can be casted to an java.lang.Object
, not a String
. If you want a string representation of whatever object, you have to invoke the toString()
method; this is not the same as casting the object to a String.
No, Integer
and String
are different types. To convert an integer to string use: String.valueOf(integer)
, or Integer.toString(integer)
for primitive, or Integer.toString()
for the object.