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.
We can convert int to String in java using String. valueOf() and Integer. toString() methods. Alternatively, we can use String.
In Java, we can use Integer. valueOf() and Integer. parseInt() to convert a string to an integer.
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.
You can't cast from int to Number because int is a primitive type and Number is an object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With