<p>Can someone give me an example of ClassCastException or help me understand this:</p>
<p>
[quote]
Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. For example, the following code generates a ClassCastException:</p>
<pre><code> Object x = new Integer(0);
System.out.println((String)x);
</code></pre>
<p>
[/quote]
</p>
<p>I think it means the code in the example incorrectly cast the object x. </p>
<p>This seems to be about polymorphism. The first line is correct because an Integer object is-an Object, so by inheritance an object variable can refer to an Integer Object.</p>
<p>The second value is invalid because String and Integer objects are not related to each other by inheritance or interfaces. </p>
<p>The cast in the println method is completely redundant because the toString method from the Integer class will automatically return a string version of the Integer object.</p>
<p>Yeah Techhexium covered it.
Casting doesn’t change one type to another per se, but just tells the compiler that it’s ok to treat a type that already was another as said type.</p>
<p>hmm I can’t see a Multiple choice problem that could come out of this concept… Anybody wanna make an example problem?</p>
<p>Seems like they could throw one of those “what will happen if you run this code” type things.</p>