• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array

 
Pramod P Deore
Ranch Hand
Posts: 632
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
4

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




}
}
 
Ankit Garg
Sheriff
Posts: 9521
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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};
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic