Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

array

 
Hasitha Randika
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class A{
public static void main(String ar[]){
int[][] a ={{1,2,},{3,4}};
int[] b = (int[]) a[1];//line 1
Object o1 = a;//line2
int[][] a2 = (int[][]) o1;//line3
int[] b2 = (int[])o1;//line4
System.out.println(b[1]);
}
}
i don't understand this one
what will hapen line1,2,3,4 executes
 
Abdullah Mamun
Ranch Hand
Posts: 99
Eclipse IDE Mac
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int[][] a ={{1,2,},{3,4}};

First of all, Mind that in Java array is Object so it can be cast to Object as well. Now lets see what happens after the assignment...
a[0] = {1, 2}
a[1] = {3, 4}

int[] b = (int[]) a[1];//line 1
After this line...
b[0] = 3
b[1] = 4

Object o1 = a;//line2
Here the whole array is converted to Object as I said before

int[][] a2 = (int[][]) o1;//line3
Here again the object converted to the array. Its alright because the object is holding a two dimensional array of int

int[] b2 = (int[])o1;//line4
this line will give a runtime exception because you cannot cast a two dimensional array into a one dimensional array

System.out.println(b[1]);
This line will print 4
 
dhwani mathur
Ranch Hand
Posts: 621
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wow!!! Al Mamun

This one is superbb explanation
 
srinivas sridaragaddi
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Excellent explanation Al Mamum!!


Can you please answer posts which i have posted today. It will be a great help.
 
Hasitha Randika
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks al mamum it was a great. now i sort out my issue. thanks for the corporation
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic