Page 262 , Question 7 1 class Zippy { 2 String[] x; 3 int[] a[] = { {1,2} ,{3} } ; 4 Object c = new long[4]; 5 Object[] d =x ; 6 }
answers is compilation succeeds , but it's not the case , Since x is not initalized and we are trying to assign un-initialize variable at line 5. Compilation should fail at 5.
Is my understanding correct. Book give answer that compilation succeeds.
Gudimella Chandana
Greenhorn
Joined: Dec 28, 2006
Posts: 7
posted
0
Hi Srini,
The class variables will be initialized to their default values. So in your example String x will be initialized to null.
Try this code
public class example{ public static void main(String args[]){ String[] x; int[] a[] = { {1,2} ,{3} } ; Object c = new long[4]; Object[] d =x ; } }
Then it will give a compilation error as the member variables have to be initialized explicitly..
Hope this clarifies your doubt.
Gudimella Chandana
Greenhorn
Joined: Dec 28, 2006
Posts: 7
posted
0
Sorry, small rectification, please read the word member variables as local variables.
jan ter avest
Ranch Hand
Joined: Dec 18, 2006
Posts: 46
posted
0
Gudimella, tip:
You can edit your posts by clicking on the blocknote+pencil symbol!
SCJP1.5 SCWCD1.5
John Lincoln
Ranch Hand
Joined: Feb 11, 2003
Posts: 192
posted
0
Hi,
What chandanna, said is correct. Since in the question class zippy, all the variables are instance variables,which do need to be intialized.
But i think, the question is regarding Casting. Array X is of type String and object d is type of Object. Since all the objects in java inherit from class "Object", you can use Object to refer to any other type of object. Compiler will not complain. At run-time, it will throw a ClassCast Exception.
Hope this helps
thanks
Srinivas Chowdary
Greenhorn
Joined: Jan 06, 2007
Posts: 5
posted
0
Thank you guys , Sorry i didn't pay attention that it's member of CLASS. Yes i agree with you guys.