Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array problem

 
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 ObjArrayTest
{
public static void main(String [] args)
{
int[] x = new int[3];
int[][] a = {{1,2},{3}};
Object c = new long[3];
Object d = x;
//Object[] e = x;//Error; Why?please expalin it in brief.



String[] z;
Object[] s = z;/*Error; in K&B they say that this code compile but compiler said that variable z might not have been initialized ; please exaplai it in brief*/
}
}
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Object[] e = x; //Error; Why? please expalin it in brief.


As x is of type int[], means array of primitive int. And int is neither an object nor a subclass of Object. So it cannot covert int[] to Object[] or Integer[].

String[] z;
Object[] s = z; /*Error; in K&B they say that this code compile but compiler said that variable z might not have been initialized ; please exaplai it in brief*/

K&B does not say this.
If you write this code inside a method, you have to initialize z.
But if you write this code inside a class, but not in a method or not in any initializer block then initialization of z to null is automatically done for you by compiler.

try this one:
class Test{
String[] z;
Object[] s = z;
}

now try this one:


class Test{
{String[] z;
Object[] s = z;}
}

one more:


class Test{
static {String[] z;
Object[] s = z;}
}
 
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
A primitive array can be assigned to a reference of type Object

int[] arr = {1};
Object obj = arr; //OK
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic