File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "array" Watch "array" New topic
Author

array

Hasitha Randika
Ranch Hand

Joined: Sep 04, 2007
Posts: 50
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

Joined: Mar 19, 2007
Posts: 99

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


MooN
dhwani mathur
Ranch Hand

Joined: May 08, 2007
Posts: 621
Wow!!! Al Mamun

This one is superbb explanation
srinivas sridaragaddi
Ranch Hand

Joined: Jul 24, 2007
Posts: 225
Excellent explanation Al Mamum!!


Can you please answer posts which i have posted today. It will be a great help.


SCJP 5.0<br /> <br />"Skills are started with learning and mastered with improvement. Nothing is hereditary except death" BUDDHA...
Hasitha Randika
Ranch Hand

Joined: Sep 04, 2007
Posts: 50
thanks al mamum it was a great. now i sort out my issue. thanks for the corporation
 
GeeCON Prague 2014
 
subject: array