It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes RuntimeException 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 "RuntimeException" Watch "RuntimeException" New topic


sandhi mridul
Ranch Hand

Joined: Jan 25, 2008
Posts: 71

Does this code throw RuntimeException?

I tried no error and no exception.
This I found in MasterExam and the answer says Line 1 will throw RuntimeException however will compile fine.

Nabila Mohammad
Ranch Hand

Joined: Nov 05, 2007
Posts: 661

I had tried a similiar program.
You are trying to downcast t1 to parent class to base class.
In that case (for me and as mentioned in the book) it threw a Class Cast Exception.
Because during compile time the compiler thinks that t1 can be of type T2.
But doesn't know that for sure.
When it runs,it realises its not and throws a class cast exception.
Try writing a method and inheriting it.And writing a complete new method in the base class.
And try accessing the base class (new) method with an object of parent class(after type casting it to the base class)
You will get an exception.

Hope it made a little bit clear.

The future belongs to those who believe in the beauty of their dreams.Dream BIG!
Swati Kadam
Ranch Hand

Joined: Mar 05, 2008
Posts: 39
You have to make the following change in the code:
class T1{}

class T2 extends T1{}
class T3 extends T1{}
public class Test{
public static void main(String []arg)
T1 t1=new T1();
T2 t2=new T2();
T3 t3=new T3();
t2=(T2)t1; //line 2
See at line 2 t1 is typecasted to T2...
Type of the actual objet denoted by reference at runtime, is checked...
In your program the reference t1 was denoting objet of class T1..
Now in the above program at runtime, reference t1 is denoting objet of type no runtime exception..
Hope this clears....

SCJP / Preparing For SCWCD
I agree. Here's the link:
subject: RuntimeException
It's not a secret anymore!