classcastexception in java 1

classcastexception in java

Object someStringAsObject="Hello";
String asString=(String)someStringAsObject;//works
Integer asInteger=(Integer)someStringAsObject;//throws ClassCastException because it is a String and not an Integer

Here is what the above code is Doing:
1. Declare a variable of type Object and assign it a String.
2. Declare a variable of type String and assign it the value of the Object variable.
3. Declare a variable of type Integer and assign it the value of the Object variable.

The first two lines work because the Object variable is a String and the String variable is a String.
The third line throws a ClassCastException because the Object variable is a String and the Integer variable is an Integer.

Similar Posts