Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; 

Thanks.

like image 752
user710818 Avatar asked Jan 23 '12 14:01

user710818


People also ask

Can int be cast to String Java?

We can convert int to String in java using String. valueOf() and Integer. toString() methods. Alternatively, we can use String.

Can you cast String Integer?

In Java, we can use Integer. valueOf() and Integer. parseInt() to convert a string to an integer.

Can you cast to a String in Java?

String Type Casting and the toString() Method In short, the main task of using this syntax is casting a source variable into the String: String str = (String) object; As we know, every class in Java is an extension, either directly or indirectly, of the Object class, which implements the toString() method.

Can Integer be cast to number Java?

You can't cast from int to Number because int is a primitive type and Number is an object.


1 Answers

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.

like image 130
Bhushan Avatar answered Oct 21 '22 09:10

Bhushan