| Author |
Array problem
|
Pramod P Deore
Ranch Hand
Joined: Jul 15, 2008
Posts: 629
|
|
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*/ } }
|
Life is easy because we write the source code.....
|
 |
Punit Singh
Ranch Hand
Joined: Oct 16, 2008
Posts: 952
|
|
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;} }
|
SCJP 6
|
 |
Ankit Garg
Saloon Keeper
Joined: Aug 03, 2008
Posts: 9191
|
|
A primitive array can be assigned to a reference of type Object int[] arr = {1}; Object obj = arr; //OK
|
SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
|
 |
 |
|
|
subject: Array problem
|
|
|