• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array assignment doubt??

 
Joe Harry
Ranch Hand
Posts: 10124
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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??
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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[].
 
Peter Heide
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10124
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 502
Java jQuery Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes, when you try to cast object to incompatible types result in java.lang.ClassCastException exception which is runtime exception.

hth,
 
Peter Heide
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Jothi Shankar Kumar, I think you are right.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic