jQuery in Action, 3rd edition
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


Pramod P Deore
Ranch Hand

Joined: Jul 15, 2008
Posts: 632

package arrayTest;

class CastArrayTest
public static void main(String [] args)
int[][] a = {{1,2},{3,4}};
int[] b = (int[])a[1];/* But when we write as <int[] b = (int[])a>it gives error . WHY? please explain in brief.*/

for (int i=0;i<b.length;i++)
System.out.println (b[i]);

//Above code compile and run succesfully but what happens in code below

int[][] x = {{4,5},{6,6}};
int[] y = (int[])x[1][1];//Error; inconvertible types

for (int i=0;i<b.length;i++)
System.out.println (y[i]);

//First code run succesfully and print output as :3

//Then why the second code not print output as : 6


Life is easy because we write the source code.....
Ankit Garg

Joined: Aug 03, 2008
Posts: 9463

int[][] a = {{1,2},{3,4}};
int[] b = (int[])a[1];

This code will compile correctly. Even the cast is not necessary. But if you remove the [1],

int[][] a = {{1,2},{3,4}};
int[] b = (int[])a; //a is a 2-d array while b is a 1-d array

then you will basically try to squeeze a 2-d array into a 1-2 array. That is not allowed. It is like trying to put two people in one shorts or two brains in one skull. That is not allowed. Also the second code will not compile as you are trying to assign a single value to an array

int[][] x = {{4,5},{6,6}};
int[] y = (int[])x[1][1];

This code will try to assign the value 6 into an array. This is not allowed. It is like doing this

int[] y = 6;

but the correct way to assign 6 to the array would be

int[] y = {6};

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
I agree. Here's the link: http://aspose.com/file-tools
subject: Array
jQuery in Action, 3rd edition