wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Array assignment doubt?? 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 "Array assignment doubt??" Watch "Array assignment doubt??" New topic
Author

Array assignment doubt??

Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9243
    
    1

Hi Guys,

Consider the code below from the K&B book,




Please help me understand the O/P as to why it gives a run time error??


SCJP 1.4, SCWCD 1.4 - Hints for you, SCBCD Hints - Demnachst, SCDJWS - Auch Demnachst
Did a rm -R / to find out that I lost my entire Linux installation!
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24166
    
  30

Well, these two lines:

int [][] a2 = (int [][])o1;
int [] b2 = (int[])o1;

try to cast o1 to two different, incompatible types. Only one of them can possibly succeed; these two types can't be interconverted. The first line succeeds, since o1 points to the original "a", which is indeed an int[][]. Therefore the second line fails, because o1 is not an int[].


[Jess in Action][AskingGoodQuestions]
Peter Heide
Ranch Hand

Joined: Nov 04, 2006
Posts: 31
Ernest answer is correct.

o1 is an Object that points to a two-dimensional array.
If you want you can cast it to a two-dimensional array.
Then you can assign one dimension to the one-dimensional array b2.

The following code works:



SCJA
Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9243
    
    1

So, the point is when we cast a one dimensional array to a 2 dimensional array and vice versa, it gives us a run time error?? Am I right guys??

Please confirm.
Prabhu Venkatachalam
Ranch Hand

Joined: Nov 16, 2005
Posts: 502

yes, when you try to cast object to incompatible types result in java.lang.ClassCastException exception which is runtime exception.

hth,


Prabhu Venkatachalam<br />SCJP 1.4,SCWCD 1.4<br />prabhu.venkatachalam@gmail.com
Peter Heide
Ranch Hand

Joined: Nov 04, 2006
Posts: 31
Dear Jothi Shankar Kumar, I think you are right.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Array assignment doubt??
 
Similar Threads
Conversion.....
Threads Using Static Method
Object points to double array, yet when casting it to single array, it causes Runtime error
File Upload Max Size
arrays