• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

array

 
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 99
Mac Eclipse IDE
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 621
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Wow!!! Al Mamun

This one is superbb explanation
 
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks al mamum it was a great. now i sort out my issue. thanks for the corporation
reply
    Bookmark Topic Watch Topic
  • New Topic