| Author |
Casting an array
|
Harsh Pensi
Ranch Hand
Joined: Aug 05, 2009
Posts: 67
|
|
Why is the exception thrown?
|
SCJP6 - 93% SCWCD5 - 97%
|
 |
Deepak Bala
Bartender
Joined: Feb 24, 2006
Posts: 6588
|
|
This code snippet should help
|
SCJP 6 articles - SCJP 5/6 mock exams - SCJP Mocks - SCJP 5 Mock exam (Word document ) - SCJP 5 Mock exam in Java.Inquisition format
|
 |
Harsh Pensi
Ranch Hand
Joined: Aug 05, 2009
Posts: 67
|
|
So you're saying that since runtime class of Number[] na in the code is [Ljava.lang.Number we cannot cast it to Integer[]. Which is corrected by this code:
But what about following code:
Since the runtime class of oa is [Ljava.lang.String; shouldnt we be able to cast it to String[] ?
|
 |
Deepak Bala
Bartender
Joined: Feb 24, 2006
Posts: 6588
|
|
Harsh Pensi wrote:So you're saying that since runtime class of Number[] na in the code is [Ljava.lang.Number we cannot cast it to Integer[]. Which is corrected by this code:
But what about following code:
Since the runtime class of oa is [Ljava.lang.String; shouldnt we be able to cast it to String[] ?
I am able to do it without a RuntimeException
Outputs 3. Do you see a different result ?
|
 |
Deepak Bala
Bartender
Joined: Feb 24, 2006
Posts: 6588
|
|
|
I am using JDK_1_6_06 under Win XP 64 bit
|
 |
Harsh Pensi
Ranch Hand
Joined: Aug 05, 2009
Posts: 67
|
|
Thanks for the replies. I guess my RAD is just playing with me. It is giving Exception on this line if I have more code below if not its running fine.
|
 |
Salil Vverma
Ranch Hand
Joined: Sep 06, 2009
Posts: 219
|
|
Hey Harsh,
This issue does not look me like of RAD region being I executed the code using the command line/eclipse in java 5 and I also got the class cast exception at run time.
I guess, the root cause is something else. Can it be running in some of our friends machine just because they have java 6 rather than java5. Btw if you tweak the code a bit number to integer casting works fine. The below code works fine
Regards
Salil Verma
|
Regards
Salil Verma
|
 |
Ninad Kulkarni
Ranch Hand
Joined: Aug 31, 2007
Posts: 774
|
|
See the code below
The code given above will compiles but throws runtime exception but if you remove comment on line number 5 then the above code will compiles and runs fine.
after line number 5 actual super class reference refer to sub class object so casting to Integer[] successfull at runtime but when super class reference refer to object of itself (that is commenting line number 5) then casting at line number 6 throws exception at runtime.
|
SCJP 5.0 - JavaRanch FAQ - Java Beginners FAQ - SCJP FAQ - SCJP Mock Tests - Tutorial - JavaSE7 - JavaEE6 -Generics FAQ - JLS - JVM Spec - Java FAQs - Smart Questions
|
 |
 |
|
|
subject: Casting an array
|
|
|