Why cannot cast Integer to String in java?

后端 未结 11 2555
时光取名叫无心
时光取名叫无心 2020-11-29 18:00

I found some strange exception:

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

How it can be possible

11条回答
  •  时光取名叫无心
    2020-11-29 19:00

    Why this is not possible:

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

          Object
         /      \
        /        \
    String     Integer
    

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

          Object
         /
        /
       A
      /
     /
    B
    

    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,

    or

    Integer.toString() for the object.

提交回复
热议问题