This week's book giveaway is in the Android forum.
We're giving away four copies of Head First Android and have Dawn & David Griffiths on-line!
See this thread for details.
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

Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Array assignment doubt??" Watch "Array assignment doubt??" New topic

Array assignment doubt??

Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9935

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, Certified Scrum Master
Did a rm -R / to find out that I lost my entire Linux installation!
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24189

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:

Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9935

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.


Prabhu Venkatachalam<br />SCJP 1.4,SCWCD 1.4<br />
Peter Heide
Ranch Hand

Joined: Nov 04, 2006
Posts: 31
Dear Jothi Shankar Kumar, I think you are right.
Don't get me started about those stupid light bulbs.
subject: Array assignment doubt??
It's not a secret anymore!