File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Runtime Exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Runtime Exception " Watch "Runtime Exception " New topic

Runtime Exception

Raghu Shree
Ranch Hand

Joined: Mar 18, 2005
Posts: 143

The above code show runtime exception as below

Exception in thread "main" java.lang.ClassCastException
at CEx.main(

could any one explain whats wrong in this code?

Raghu J<br />SCJP 1.4<br /> <br />The Wind and waters are always<br />on the side of the ablest navigators.<br /><a href="" target="_blank" rel="nofollow">SCJP Group</a><br /><a href="" target="_blank" rel="nofollow">SCWCD Group</a>
vinuharan haran
Ranch Hand

Joined: Feb 26, 2005
Posts: 64
At runtime the object is tested for the type casted.
The Sub class "is a" base class and the reverse is not true.
Hence u get the error.
It compiles fine as only the cast type(not the true object)is checked at compile time.
Hope this helps...
sethu chiyan

Joined: Apr 05, 2005
Posts: 10
Hi, I have replied for some similar kind of question in another topic.

class Base {}
class Sub extends Base {}
class Sub2 extends Base {}
public class Mobile
public static void main(String argv[]){
Base b=new Base();
Sub s=(Sub) b; //Line no 10


Yes! its a Runtime error, coz of not following hierarchy reflection. you can't assign the obj of base class to the derived class object. But u can assign the obj of derived class to the base class object.

Example code for ur prg: No Compiler or runtime ERROR.

Sub _sub = new Sub();
b = _sub;
Sub2 _sub2 = new Sub2();
b = _sub2;

The point is Derived class may have some additional functionality of Base class, So u cant assign the base class object to derived class object.

The compiler would have shown the error if you had not type cast the b to (Sub). the copiler only checks the r.side operand sink with l.side operand in the assignment operator.

This cast incompatability will come to know only at the runtime.

with regards,
Raghu Shree
Ranch Hand

Joined: Mar 18, 2005
Posts: 143

I make one simple change in your code. Its now work fine.
I don't know whats done inside of the jvm. Could any one explain me
Rahul Bhosale
Ranch Hand

Joined: Mar 10, 2005
Posts: 77

b now points to another object which is legal. Though b of type Base it is referring to a new object which is its subclass so it is legal.
no when you apply a cast to b

you are doing a type cast on the reference object which is of type Sub, so it is legal.

Raghu Shree
Ranch Hand

Joined: Mar 18, 2005
Posts: 143

Why it is not valid ?
I agree. Here's the link:
subject: Runtime Exception
It's not a secret anymore!