In your case, casting is not required, you need to call toString ().
Integer i = 33; String s = i.toString(); //or s = String.valueOf(i); //or s = "" + i;
Casting. How it works?
Given:
class A {} class B extends A {}
(BUT)
|
(B)
B b = new B();
A and B in the same inheritance tree, and we can do this:
a = new A(); b = (B)a;
The compiler must allow anything that can run at runtime. However, if the compiler knows with 100% that the throw cannot work, compilation will fail.
Given:
class A {} class B1 extends A {} class B2 extends A {}
(BUT)
/ \
(B1) (B2)
B1 b1 = new B1(); B2 b2 = (B2)b1;
Error: Non-convertible types B1 and B2. The compiler knows with 100% that the throw cannot work. But you can trick the compiler:
B2 b2 = (B2)(A)b1;
but anyway at runtime:
Exception in thread "main" java.lang.ClassCastException: B1 cannot be attributed to B2
in your case:
(an object)
/ \
(Integer) (String)
Integer i = 33;
at runtime: exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be passed to java.lang.String
Dmitry Sokolyuk Dec 21 '16 at 7:57 2016-12-21 07:57
source share