File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "arrays" Watch "arrays" New topic


Ajay Kumar Rana

Joined: Feb 27, 2008
Posts: 13
for the code below

public class Dims{
public static void main(String[] args){
int [][] a = { {1,2}, {3,4} };
int [] b = (int []) a[1];
Object o1 = a;
int [][] a2 = (int[][])o1;
int[] b2 = (int[])o1;

an exception is thrown at runtime. Why the error is not thrown at compile time although o1 is two dimensional array reference and b2 is one dimensional.I am not able to grasp this concept.Please explain.
Anubhav Anand
Ranch Hand

Joined: May 18, 2007
Posts: 341

o1 is of type object. Object is the base class and can hold any kind of reference. So when you allocate a to o1 it happily does that.

Similarly, when you say
Compiler, thinks that it is some object being casted and happily says you can go ahead. So, we may say that compiler just is a type checker and synatx matcher. It found that we can cast object to array so it gave the go ahead.

But, the values being held in objects are available (i.e checked) only at runtime. So, you get the cast exception for casting a two dimensional array object to single dimension.

Hope that solves your problem.
I agree. Here's the link:
subject: arrays
It's not a secret anymore!