This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

arrays

 
Ajay Kumar Rana
Greenhorn
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
System.out.println(b[1]);
}
}

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
Posts: 341
Firefox Browser Java Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic