user710818 user710818 - 1 year ago 135
Java Question

Why cannot cast Integer to String in java?

I found some strange exception:

java.lang.ClassCastException: java.lang.Integer
cannot be cast to java.lang.String

How it can be possible? Each object can be casted to String, doesn't it?

The code is:

String myString = (String) myIntegerObject;


Answer Source

Why this is not possible:

Because String and Integer are not in the same Object hierarchy.

     /      \
    /        \
String     Integer

The casting which you are trying, works only if they are in the same hierarchy, e.g.


In this case, (A) objB or (Object) objB or (Object) objA will work.

Hence as others have mentioned already, to convert an integer to string use:

String.valueOf(integer), or Integer.toString(integer) for primitive,


Integer.toString() for the object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download