This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Devaka's Exam Lab Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Devaka Watch "Devaka New topic
Author

Devaka's Exam Lab Question

Mansi Agarwal
Ranch Hand

Joined: Apr 11, 2012
Posts: 53


Dont understand how the conversion. Please help..
Don Redd
Ranch Hand

Joined: Jan 05, 2012
Posts: 82

Hi,
First look at compile time evaluation of below statements




line 15: b=(C) m; this line has two castings 1) from m to C(Since m is of Interface type compiler skips check, it passes)
2) from C to b ( since variable b is of Type B which can refer to subclass C,this test passes as well)

work similarly for rest,,,,

second at runtime, you have to check for incompatible assignments, as show in below example


the above piece compiles fine but fails at run time
Don Redd
Ranch Hand

Joined: Jan 05, 2012
Posts: 82

one more hint:

the below code compiles and runs fine..........
gurpeet singh
Ranch Hand

Joined: Apr 04, 2012
Posts: 924
    
    1

i'm posting this for the third consecutive time. the question that deals with casting can be confusing and under pressure one can mark wrong answer.the following rules are really helpful i solving casting questions. they are derived from concepts only but are much faster to work with.

consider the generalize scenario

A B = (C) D

1. C and D should have relationship, either C is-a D or D is-a C, otherwise COMPILER ERROR. e.g Dog d = new Dog() ; String s = (String)d;

2. A and C should be of the same type of C should be subtype of A, otherwise COMPILER ERROR.

3. D should refer to a type that is same as of C or subtype of D, otherwise Runtime error.

also if D is null then it can be typecasted to anything(since null can be assigned to anything, except primitives) and the result will be null.

i recommend you follow the above rules and try to solve the question once more and definitely you will be able to crack it. also these are not rules/official, they have been derived from the common concepts that we know. if you are still not able to understand then please post it . we'll help you out
Mansi Agarwal
Ranch Hand

Joined: Apr 11, 2012
Posts: 53
Thanks Don and Gurpreet.

I will keep those points in my mind.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Devaka's Exam Lab Question